计算C中的用户输入百分比

时间:2015-09-23 06:01:05

标签: c percentage

对于家庭作业,我必须计算C中用户输入百分比的百分比折扣,每次运行此程序时,它都会将结果返回原始价格而不是折扣百分比(对于家庭作业,我被告知如果没有百分比运算符。)

#include <stdio.h>

int main(){

    double price_book;
    int percent;
    double grand_total;

    printf("What is the price of the book?\n");
            scanf("%lf", &price_book);

    printf("The Price of the book before discount is %.2lf\n\n",price_book);


    printf("How much percent discount is to be applied?\n");
            scanf("%d", &percent);

    grand_total = (100-percent)/100 * price_book;

    printf("\nThe total after discount is %.2lf\n", &grand_total);

    return 0;
}

3 个答案:

答案 0 :(得分:1)

表达式(100-percent)/100整数表达式,所有涉及的值都是整数,因此得到整数除法,这将得到值0

而是使用浮点值:(100.0-percent)/100.0

答案 1 :(得分:1)

除了你需要解决的Joachim Pileborg said

printf("\nThe total after discount is %.2lf\n", &grand_total); 

将其更改为:

printf("\nThe total after discount is %.2lf\n", grand_total); 

&运算符用于获取地址。并且您可能不需要printf的地址,就像您需要scanf一样。粗略地说,在scanf()中,您需要使用地址将控制台输入/用户输入放入变量中。

答案 2 :(得分:0)

我想您可以查看下面的代码,这是有效的,price_bookpercent一起计算,请查看以下内容。

#include <stdio.h>

int main(){

    double price_book;
    int percent;
    double grand_total;

    printf("What is the price of the book?\n");
    scanf("%lf", &price_book);

    printf("The Price of the book before discount is %.2lf\n\n",price_book);

    printf("How much percent discount is to be applied?\n");
    scanf("%d", &percent);

    grand_total = price_book - ( (percent)/100.0 * price_book);

    printf("\nThe total after discount is %.2lf\n", grand_total);

    return 0;
}