I'm trying to find the time taken to travel over an inputted distance going at a constant speed in C. The code I have functions but the output is printed as 0? Any idea what is going wrong?
#include <stdio.h>
#include <stdlib.h>
int main() {
int distance, speed = 80;
float time;
// This is how to read an int value
printf("Please enter a distance in kilometers to be covered at 80KPH. \n");
scanf("%d", & distance);
printf("You typed: %d\n", distance);
printf("\n");
time = distance / speed;
printf("It will take you %.2f to cover ", time);
}
Run Code Online (Sandbox Code Playgroud)
因为两个操作数是整数,所以编译器生成整数除法的代码.但你想要真正的分裂.因此,将一个或多个操作数强制转换为浮点类型,编译器将发出实际除法的代码.
time = (float) distance / time;
Run Code Online (Sandbox Code Playgroud)
整数分工是你在小学学到的.因此,例如,11/3是3余数2.在C中,表达式11/3的计算结果为3.这是整数除法.在你的情况下,似乎分子(距离)小于分母(时间),因此表达式
distance / time
Run Code Online (Sandbox Code Playgroud)
评估为0.
这是由除法运算符的超载引起的常见混淆.如果两个操作数都是整数,则此运算符表示整数除法,否则为实数除法.
要学习的关键点是,操作数的类型决定了是使用整数还是实数除法.存储结果的变量类型对此选择没有影响.
| 归档时间: |
|
| 查看次数: |
699 次 |
| 最近记录: |