2017-07-29 76 views
-2

我已經在Code :: Blocks上創建了這個測試分數程序,根據最大可達點數和他們在測試中達到的分數計算學生測試的百分比,但是我得到的所有情況都是0%結果,我不知道爲什麼。爲什麼在這個程序中所有情況下都會得到0%的結果?

有人可以幫我解釋一下嗎?

#include <cstdio> 
#include <cstdlib> 
#include <iostream> 

using namespace std; 

int main(int nNumberofArgs, char* pszArgs[]) 

{ 
    //enter the maximum reachable score 
    int maxscore; 
    cout << "Enter the highest possible score: "; 
    cin >> maxscore; 

    //enter the reached score 
    int score; 
    cout << "Enter your score: "; 
    cin >> score; 

    //calculate percentage 
    //what's wrong here with the percentage calculation? 
    int percentage; 
    percentage = (score/maxscore)*100 ; 

    //output the results (followed by a NewLine) 
    cout << "Your result is: "; 
    cout << percentage <<"%"<< endl; 

    //wait until user is ready before terminating the program to allow the user 
    //to see the program results 
    cout << "Pres Enter to continue..."<<endl; 
    cin.ignore(10, '\n'); 
    cin.get(); 
    return 0; 
} 
+5

關鍵字:整數算術,」score/maxscore「d oes不會產生你期待的結果 – VTT

+0

@VTT那麼它將如何工作? –

+0

通過將int百分比更改爲浮點百分比 – Kartik

回答

-2

您的問題是使用整數百分比。使用浮點數爲小數位數支持。這裏是一個浮動的代碼示例:

#include <cstdio> 
#include <cstdlib> 
#include <iostream> 

using namespace std; 

int main(int nNumberofArgs, char* pszArgs[]) 

{ 
    //enter the maximum reachable score 
    int maxscore; 
    cout << "Enter the highest possible score: "; 
    cin >> maxscore; 

    //enter the reached score 
    int score; 
    cout << "Enter your score: "; 
    cin >> score; 

    //calculate percentage 
    //what's wrong here with the percentage calculation? 
    float percentage; 
    percentage = (score/maxscore)*100 ; 

    //output the results (followed by a NewLine) 
    cout << "Your result is: "; 
    cout << (int) (percentage+0.5) <<"%"<< endl; // fast the Float to int for Zero decimal and add 0.5 befördert fast for rounding. 

    //wait until user is ready before terminating the program to allow the user 
    //to see the program results 
    cout << "Pres Enter to continue..."<<endl; 
    cin.ignore(10, '\n'); 
    cin.get(); 
    return 0; 
} 
+0

Typo:Float-> float。我會自己改變它,但如果你正在編輯中,我不想擠壓東西。 – user4581301

+0

這個答案無論如何都是錯誤的,因爲它仍然會使用相同的整數算術表達式計算百分比,併產生0.0f ... – VTT

+1

提示:首先浮點'score'。 – tadman

1

你應該改變:

percentage = (score/maxscore)*100 ; 

percentage = (score*100)/maxscore ; 

因爲score/maxscore是threated爲整數,所以「地板()版「爲0,當乘以100時,它只能是100的倍數。

相關問題