2017-02-26 45 views
-2

此處的所有內容都以我希望的方式工作,但函數「tipConvert(tip)」除外。提示計算 - 將數字更改爲小數點代碼

我希望它將數字(如15)更改爲.15,該數字可能是百分比的十進制表示形式。

#include <stdio.h> 

float tipConvert(int tip); 

int main() 
{ 
    char value; 
    int intValue tip; 
    float bill, result; 

    intValue = 1; 

    while(intValue == 1) 
    { 
     printf("Would you like to calculate a tip: y or n?\n"); 
     scanf("%s", &value); 
     if(value == 'y') 
     { 
      printf("Enter the bill amount:\n"); 
      scanf("%f", &bill); 
      printf("Enter the tip amount as an integer:\n"); 
      scanf("%i", &tip); 
      result = tipConvert(tip)*bill; 
      printf("Tip for %.2f is %.2f\n", bill,result); 
     } 
     else if(value == 'n') 
     { 
      printf("Thank you for using Tip Calculator."); 
      break; 
     } 
     else 
      printf("Please select y or n.\n"); 

    } 
    return 0; 
} 

float tipConvert(int tip) 
{ 
    return tip/100; 
} 
+0

請嘗試使您的問題標題不太通用。什麼是「計算」? –

+0

你是dividint 2個整數;並將結果存儲爲int。因此,當您的分區結果爲0.xx時,它將舍入爲零。因此,提示/ 100.0:這應該工作。 –

回答

1

的問題是,一個int不能存儲任何十進制數,並調用尖/ 100時,編譯器認爲這是一個整數除法,並返回一個int(在你的例子0)和施放,爲浮之後。

告訴編譯器使用浮點除法的最簡單方法是使用100.0f除以浮點文字而不是int文字。這應該解決這個問題。
或者,您可以投擲提示以前浮動。

+0

只爲小費閱讀浮動不是最簡單的嗎? – stark

+0

當然,你可以這樣做,你也可以設置參數爲float並傳遞一個int,然後將其轉換爲float。 –

相關問題