我正处于编程类中,我们刚从python切换到C.我遇到了一些麻烦,因为C似乎没有像python那样轻松地执行数学运算,或者我错过了在C语言中谈论数学的东西
对于我的家庭作业,我正在写收集了多少英里每加仑用户的汽车节目得到多少,每加仑的燃气费,有多少英里,他们每个月开车.然后,该计划告诉他们他们可以期望为当月的天然气支付多少钱.我目前的代码如下:
#include <stdio.h>
int main () {
int mpg, miles;
double gas_price;
printf("How many miles per gallon does your car get?\n");
scanf("%d", &mpg);
printf("What is the price of gasoline per gallon?\n");
scanf("%lf", &gas_price);
printf("How many miles do you drive in a month?\n");
scanf("%d", &miles);
printf("The cost of gas this month is $%.2lf\n", miles / mpg * gas_price);
printf("%d %d %d", mpg, gas_price, miles);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,值为24为"mpg",3.00为"gas_price",1000为里程,总计为$ 123.00.这是不正确的,比实际价格低约2美元.当你((1000/24)*3.00),你应该得到125均匀.我添加了一个字符串来打印出所有值以查看C在第23行中使用的公式,而mpg和gas_price是正确的,"miles"显示为值为1,074,266,112.我知道这里肯定会有一些错误,因为这会导致结果超过2美元,但我不禁认为这是相关的.
我为问题的长度道歉,但我希望尽可能具体,我完全难以理解为什么C在如此奇怪地读这个.
Mys*_*ial 14
你在这里做整数除法:
miles / mpg * gas_price
Run Code Online (Sandbox Code Playgroud)
将两个操作数中的double一个转换为第一个:
(double)miles / mpg * gas_price
Run Code Online (Sandbox Code Playgroud)
整数除法将截断小数部分.这就是你的号码关闭的原因.
你在这里有另一个错误:
printf("%d %d %d", mpg, gas_price, miles);
Run Code Online (Sandbox Code Playgroud)
您的printf格式说明符与操作数不匹配.它应该是:
printf("%d %f %d", mpg, gas_price, miles);
Run Code Online (Sandbox Code Playgroud)