我尝试制作电价计算C语言程序,但一行无效

时间:2019-12-28 16:40:54

标签: c line

我尝试制作电价计算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

2 个答案:

答案 0 :(得分:0)

在子表达式9/100中,两个操作数都是整数,因此除法是整数除法,这意味着任何小数部分都将被截断,因此其求值为0。

如果更改为浮点常量,则会得到浮点除法。因此,将以上内容更改为:

9.0/100.0

或者简单地:

0.09

答案 1 :(得分:-1)

您只需像这样(9/10)来打字((double)9 / 100)。从现在开始,它考虑将9/10的输出作为整数并将结果设为0。

在打印tax时,应该使用%lf而不是%d

#include <bits/stdc++.h>

using namespace std;

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 * ((double)9 / 100);   //This line is the problem line = doesn't work

    totalFinalMoney = totalMoney + tax; 

    printf("Tax is %lf\n", tax);  // a line to show that the tax isn't being caluculated properly

    printf("The final usage price is %lf.", totalFinalMoney);
}