2015-09-23 36 views
-1

對於作業,我必須計算C中用戶輸入百分比的折扣百分比,每次運行此程序時,它都會以原始價格返回結果,而不是折扣百分比(作業I是告訴做到不百分比操作。)在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; 
} 
+4

整數除法截斷。 '(100%)/ 100'始終爲0. –

+1

編譯時請啓用警告。你正試圖在你最後的'printf'中打印一個地址;你只需要'printf(「%。2lf \ n」,grand_total);'。但是'scanf'的參數是可以的,但是:這裏你需要'&'); –

+2

另外,你所說的「百分比運算符」實際上被稱爲「模數」,它的功能與百分比無關。 – Adam

回答

1

表達(100-percent)/100整數表達,所有涉及的值是整數,所以你得到整數除法,這將導致價值0

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

2

隨着你需要解決這個問題是什麼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()中,您需要將控制檯輸入/用戶輸入放入變量中的地址。

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; 
}