将两个整数相除得到 0,而我应该得到 1
Dividing two integers results 0, while I should get 1
我应该从用户那里得到距离和速度,并得到 return 时间。
这是我做的代码:
int main()
{
int distance, speed;
scanf("%d,%d", &distance, &speed);
printf("%d\n", distance / speed);
printf("%d hours and %d minutes", (distance/speed), (distance / speed)%60);
}
对于值:
10 10
我收到 0
作为输出。
这里的问题是,您没有检查 scanf()
的 return 值以确保它成功。
通过属性,scanf()
提供的格式字符串应该完全匹配输入,否则由于匹配失败,接收参数获胜'得到期望值。
格式字符串如
scanf("%d,%d", &distance, &speed);
一个输入
10 10
不合适,需要输入like
10,10
匹配格式字符串中的,
。
否则,您也可以从格式字符串中删除 ,
,并以 space 分隔格式提供输入。
[编辑]:
要强制执行浮点除法,请将您的声明更改为
printf("%f\n", ( (float)distance / speed ) );
printf("%f hours and %d minutes", ( (float)distance / speed ), (distance / speed)%60);
您需要输入 10,10
,因为这是您 scanf()
的要求。
那你的计算当然是错误的。您将获得 1
和 1
小时和分钟。
我应该从用户那里得到距离和速度,并得到 return 时间。 这是我做的代码:
int main()
{
int distance, speed;
scanf("%d,%d", &distance, &speed);
printf("%d\n", distance / speed);
printf("%d hours and %d minutes", (distance/speed), (distance / speed)%60);
}
对于值:
10 10
我收到 0
作为输出。
这里的问题是,您没有检查 scanf()
的 return 值以确保它成功。
通过属性,scanf()
提供的格式字符串应该完全匹配输入,否则由于匹配失败,接收参数获胜'得到期望值。
格式字符串如
scanf("%d,%d", &distance, &speed);
一个输入
10 10
不合适,需要输入like
10,10
匹配格式字符串中的,
。
否则,您也可以从格式字符串中删除 ,
,并以 space 分隔格式提供输入。
[编辑]:
要强制执行浮点除法,请将您的声明更改为
printf("%f\n", ( (float)distance / speed ) );
printf("%f hours and %d minutes", ( (float)distance / speed ), (distance / speed)%60);
您需要输入 10,10
,因为这是您 scanf()
的要求。
那你的计算当然是错误的。您将获得 1
和 1
小时和分钟。