2014-01-18 32 views
-1

在程序中,我應該根據用戶的總分數來分配字母等級。我知道如何if/else語句即:如何計算不帶if/else語句的字母等級C++

if (score <= 100 && score > 93) 
    cout << "You have received an A"; 
else if (score <= 93 && score > 89) 
    cout << "You have received an A-"; 
else if etc.etc.etc. 

我不知道如何計算字母等級不if/else語句的字符串做到這一點使用。這些是說明:

將所有可能的字母等級存儲在一個常量字符串數組中,然後提出一個算法,使用總點數來計算數組中的索引以返回字母等級。這樣可以避免使用長串的if/else語句。

這裏是我到目前爲止(沒有所有的鐘聲和整個方案的口哨聲):

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    int userInput; 

    string gradeData[] { "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F" }; 

    cout << "What are your total number of points?: "; 
    cin >> userInput; 

    cout << "\nYour final grade is " << **INSERT CALL TO GRADE CALCULATION FUNCTION HERE** << endl; 

    system("PAUSE"); 
    return 0; 
} 

我的計劃是寫,這是否和字母等級返回功能用戶,但我真的不知道從哪裏開始。它可能涉及使用二維數組嗎?任何幫助將不勝感激。

+0

剛寫的if語句的字符串。比任何其他可能的(複雜的)解決方案更簡單和更容易理解。 –

+0

因此,給出N分的分數,你如何找到相關的字母等級?只有101個值需要考慮:0 ... 100;這不是一個非常大的陣列(但它是一個非常無聊的)。 –

+0

您被要求編寫*算法*來計算該數組中的索引。所以如果得分是94-100,你需要拿出0(給你的字符串數組)。 –

回答

1

這是做的。你必須先秤/特定範圍內的標準化值等級的正確方法。該範圍是:1 --> grades.length。其中grades.length是你的字符串數組。

現在由於字符串數組來自A --> F而不是F --> A,所以您必須通過執行grades.length - scaled_grade來反轉/翻轉等級。

例如,如果等級是100,我們縮小下來1到12之間,我們會得到11 Grades[11]是F. Grades[Grades.length - 11]是A.

下面的代碼將證明我上面的解釋。我無法解釋的東西非常好..

#include <iostream> 

int scale(int minimum, int maximum, int value, int maxrange = 1, int minrange = 0) 
{ 
    return ((maxrange - minrange) * (value - minimum))/(maximum - minimum) + minrange; 
} 

int main() 
{ 
    const std::string grades[] = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "F"}; 

    int size = sizeof(grades)/sizeof(grades[0]); 
    int grade = 0; 

    std::cout<<"Enter your grade: "; 
    std::cin>>grade; 
    std::cin.ignore(); 

    int g = size - scale(0, 100, grade, size, 1); 
    std::cout<<"Your grade is: "<<grades[g]; 
} 

現場測試案例:http://ideone.com/2qVRQS

*

stdin is set to 50, it will print C. 
stdin is set to 100, it prints A. 
stdin is set to 0, it prints F. 

*

等..

+0

這使得每個等級的標記範圍都相同。 –

+0

是的,它確實如此,但它比填充100個等級的數組要好。沒有這樣的假設,你需要分支/ if語句/開關情況等。 – Brandon

3

嘗試......

string gradeData[100] = { 
    "F", // For person not turning up and scoring nothing 
    "F", // For the person turning up and managing to sit down 
    "F", // For the person turning up and managing to face the right direction 
    "F", // For the person turning up and managing to write something in the name box 
    "F", // For the person turning up and managing to spell their name right 
    "E", // For the person able to open the question paper 

    .... 

    "C", // For the person getting 50% of the questions nearly right 

    ... 

    "A+" // For the swot at the front 

}; 

cout << "Your grade is " << gradeData[score] << endl; 
+1

我一直想知道如何獲得E級......現在我知道:) –

+2

@JeremyFriesner:在日本,我們實際上有'E'作爲字母等級,它相當於美國'F',我認爲各國不會因爲將F更改爲E是多麼容易,所以使用*** E和F;) –

+0

@AndonM。科爾曼 - 如果你有E/F,你甚至可以告訴你的僱主? –