簡體   English   中英

GPA計算器的If語句問題

[英]If statement issue with GPA calculator

在使用GPA計算器時,運行程序時遇到的問題甚至是當用戶輸入分數“ B”時,當要求輸入分數時,GPA仍然給出5的輸出,這應該不是。

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

int main()
{
    string course;
    int courses;
    int a_ = 1;
    int units;
    int gp = 0;
    int tgp = 0;
    int totalunits = 0;
    string grade;
    float gpa;

    cout << "How many courses offered" << endl;
    cin >> courses;
    while (a_ <= courses){
        cout << "Type the course code" << endl;
        cin >> course;
        cout << "Units allotted to the course" << endl;
        cin >> units;
        cout << "Input Grade " << endl;
        cin >> grade;
        if (grade == "A" || "a"){
            gp = units * 5;
        }
        else if (grade == "B" || "b"){
            gp = units * 4;
        }
        else if (grade == "C" || "c") {
            gp = units * 3;
        }
        else if (grade == "D" || "d") {
            gp = units * 2;
        }
        else if (grade == "E" || "e") {
            gp = units * 1;
        }
        else if (grade == "F" || "f") {
            gp = units * 0;
        }
        else {
            cout << "Incorrect details, Re-Input them." << endl;
        }


        tgp = tgp + gp;
        totalunits = totalunits + units;
        ++a_;

    }
    gpa = tgp/totalunits;
    cout << tgp << endl;
    cout << totalunits << endl;
    cout << "Your GPA is : " << gpa << endl;
}

由於我得到的錯誤,將switch語句更改為if語句。

如果您強制使用大寫,它將簡化所有操作。

char grade;
cin >> grade;
grade = toupper(grade);
gp = units * ('F' - grade);

嘗試一些轉換功能,例如:

int points_from_grade(char grade) {
    if (isupper(grade)) {
        return 5 - (grade - 'A');
    } else { // islower
        return 5 - (grade - 'a');
    }
}

關於C ++中的字符,需要注意的一件有趣的事情是它們具有一個關聯的數值,可以用於數學運算。

知道了這一點,您可以完成設置的一種方法是,將字符“ A”的十進制ASCII值(即65)減去60,從而為該字母等級提供所需的整數值。

例如:

cout << 'A' - 60;

將輸出整數“ 5”。

如果用戶輸入的是小寫字母“ a”,則需要使用十進制ASCII值(即97)並從中減去92。

按照該架構,您應該能夠弄清楚需要進行哪些更改才能使程序按您希望的方式運行。

作為參考,可以在以下位置找到完整的ASCII表和說明: https : //www.asciitable.com/

您可以將switch語句更改為以下形式:

// Relevant code parts

const int GRADE_A_POINTS = 5;
const int GRADE_B_POINTS = 4;
// etc.

char grade;
cin >> grade;

switch (grade) {
    case 'A':
    case 'a':
        gp = units * GRADE_A_POINTS;
        break;

    case 'B':
    case 'b':
        gp = units * GRADE_B_POINTS;
        break;

    // etc.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM