2014-08-30 37 views
0
char choice, y, n; 
float percentage; 
int marks; 
printf("Do you want to know your percentage?(y/n):\n\n"); 
scanf(" %c", &choice); 
if (choice == 'y') { 
    printf("Enter Your 2nd Sem Marks:\n\n"); 
    scanf(" %d", &marks); 
    percentage = (marks/775) * 100; 
    printf("Your 2nd Sem Percentage is %.2f", percentage); 
} else 
    printf("Thankyou!!!!\n\n\n"); 

使用上述代碼我不能計算百分比 - I得到輸出0.00 ...c編程 - 不能得到期望的輸出

例如,當我給輸入作爲536,而不是顯示導致的69.16,這表明0.00 請幫我

+3

'775' - >'775.0' – BLUEPIXY 2014-08-30 15:28:46

+0

可能重複[C中的整數除法的行爲是什麼?](http://stackoverflow.com/questions/3602827/what-is-the-behavior-of -integer-division-in-c) – juanchopanza 2014-08-30 15:37:34

+1

你已經通過評論表明你的問題的兩個答案已經奏效。還有一件事你應該做,那就是將其中一個答案標記爲「已接受」。這是回答你的問題的人從回答時間中獲益的方式之一。 – DavidO 2014-08-30 16:01:09

回答

5

由於marksint而且將永遠是小於775,表達(marks/775),經過整數除法,永遠產量爲零。您應該在表達式中強制轉換爲浮點數,或者在表達式中使用浮點數,以保留除法的其餘部分。

+0

非常感謝它的工作... – 2014-08-30 15:37:11

3

這是因爲你在做這個

percentage = (marks/775) * 100; 

而應該做到這一點

percentage = ((float)marks/775) * 100; 

記住(marks/775)會給整數作爲兩個操作數均爲整數。 Int他的情況下,536/775將根據整數除法爲0

您應該改爲執行浮動除法以獲取百分比。

+0

非常感謝....它的工作 – 2014-08-30 15:37:41

+0

請接受這是否有幫助。 – OneMoreError 2014-08-30 15:38:39