在C ++中使用多个if else语句

时间:2016-02-17 14:35:59

标签: c++

我没有编程经验,我正在为工程师开设一门名为C ++的课程。我们目前正在学习如何使用if else语句,并且我已经被困了几天,为什么我的程序没有正确执行以及我犯了错误。

我需要创建一个程序来计算和显示一个术语中的两个类的gpa。我还没有学习循环,所以我需要对两个类的计算和输入进行硬编码。问题是,当我输入两个类的任何成绩字母时,它总是将第一个if语句在两种情况下都为真。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{

    double gpa, qualityPoints, qualityPoints1, qualitypointsTotal, totalCredits, credits, credits1;
    double cqPoints, cqPoints1;
    char grade, grade1;

    cout << "Grade Point Average Calculator" << endl << endl;

    cout << "Enter the grade letter received for the first class: " << endl;
    cin >> grade;

    if (grade = 'A')
    {
        qualityPoints = 4.0;
    }
    else if (grade = 'B')
    {
        qualityPoints = 3.0;
    }
    else if (grade = 'C')
    {
        qualityPoints = 2.0;
    }
    else if (grade = 'D')
    {
        qualityPoints = 1.0;
    }

    else if (grade = 'F')
    {
        qualityPoints = 0.0;
    }

    else
    {
        cout << "Invalid Letter Grade" << endl;
    }

    cout << "How many credit hours was the class worth?" << endl;
    cin >> credits;

    cqPoints = qualityPoints * credits;

    cout << "Enter the grade letter received for the second class: " << endl;
    cin >> grade1;

    if (grade1 = 'A')
    {
        qualityPoints1 = 4.0;
    }
    else if (grade1 = 'B')
    {
        qualityPoints1 = 3.0;
    }
    else if (grade1 = 'C')
    {
        qualityPoints1 = 2.0;
    }
    else if (grade1 = 'D')
    {
        qualityPoints1 = 1.0;
    }
    else if (grade1 = 'F')
    {
        qualityPoints1 = 0.0;
    }

    else
    {
        cout << "Invalid Letter Grade" << endl;
    }
    cout << "How many credit hours was the class worth?" << endl;
    cin >> credits1;

    cqPoints1 = qualityPoints1 * credits1;

    totalCredits = credits + credits1;

    cout << "Total credit hours earned this term: " << totalCredits << endl;

    qualitypointsTotal = cqPoints + cqPoints1;

    gpa = qualitypointsTotal / totalCredits;

    cout << "Your GPA for this term is: " << gpa << endl;


    cout << "Credits: " << credits << endl;
    cout << "Credits1: " << credits1 << endl;
    cout << "qualityPoints: " << qualityPoints << endl;
    cout << "qualityPoints1: " << qualityPoints1 << endl;
    cout << "cqPoints: " << cqPoints << endl;
    cout << "cqPoints1: " << cqPoints1 << endl;
    cout << "qualitypointsTotal: " << qualitypointsTotal << endl;
    cout << "totalCredits: " << totalCredits << endl;
    return 0;

}

我非常清楚有更有效的方法可以做到这一点但是现在我只是学习基础知识,所以我希望保留与课程范围相关的答案。

谢谢!

编辑:我认为可能有必要提一下,我理解变量不需要double。我也不需要io操作或程序结束附近的任何couts。我只想弄清楚出了什么问题。 : - )

1 个答案:

答案 0 :(得分:1)

这是因为您在if语句中使用了赋值运算符&#39; =&#39;而不是比较运算符&#39; ==&#39;所以你不是要比分,你要分配给它。

有几种方法可以减少此类问题。一种是将变量声明为&#39; const&#39;越多越好;这会将不需要的分配标记为错误。另一种方法是在if语句中反转变量和字面值(即if(&#39; A&#39; == Grade)),这具有相同的效果。

此外,如果您打开所有编译器警告,您可能也会收到警告。当然,这取决于你的编译器。