如何在没有if / else语句C ++的情况下计算字母等级

时间:2014-01-18 05:59:29

标签: c++ arrays if-statement

在程序中,我应根据用户的总分数指定一个字母等级。我知道如何使用if / else语句,即:。

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

我的计划是写一个执行此操作的函数并将字母等级返回给用户,但我真的不知道从哪里开始。它可能涉及使用二维数组吗?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分: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 :(得分:2)

这是正确的方法。您必须首先在特定范围内缩放/标准化您的成绩值。该范围来自: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.

*

依旧......