我尝试编写一个计算电价的c语言程序,但是一行行不行。
这是我的代码。
#include <stdio.h>
int main()
{
int usageElectric; //amount of electricity used
int basicMoney; //basic price
int totalMoney; //total price
double usageMoneyPerKw; //kw per used price
double totalFinalMoney; //final usage price
double tax; //tax
printf("put in the amount of electricity used (kw) : "); //put in 150kw.
scanf("%d", &usageElectric);
basicMoney = 660; //basic price = $660
usageMoneyPerKw = 88.5; //kw per usage price : $88.5
totalMoney = basicMoney + (usageElectric * usageMoneyPerKw);
tax = totalMoney * (9 / 100); //This line is the problem line = doesn't work
totalFinalMoney = totalMoney + tax;
printf("Tax is %d\n", tax); // a line to show that the tax isn't being caluculated properly
printf("The final usage price is %lf.", totalFinalMoney);
return 0;
}
如果输入为 150(kw),则 TotalFinalMoney 应为 $15189.150000
任何人都可以帮我解决为什么这条线不起作用吗?
tax = totalMoney * (9 / 100);
如果工作正常,结果应该如下:
tax = 13935 * (9/100) = 1254.15
因此,最终结果应该是:
The final usage price is 15189.150000
最佳答案
在子表达式 9/100
中,两个操作数都是整数,因此除法是整数除法,这意味着任何小数部分都会被截断,因此计算结果为 0。
如果更改为浮点常量,您将得到浮点除法。因此将上面的内容更改为:
9.0/100.0
或者简单地说:
0.09
关于c - 我尝试制作一个计算电价的c语言程序,但是一行行不通,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59512806/