我沒有編程經驗,我正在一類稱爲介紹C++工程師。我們目前正在學習如何使用else語句,並且爲什麼我的程序沒有正確執行以及我犯了什麼錯誤,我一直堅持了幾天。使用多個如果C++ 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;
}
我很清楚,有更有效的方法可以做到這一點,但現在我剛學的基礎知識,所以我將不勝感激保持相關課程的範圍答案。
謝謝!
編輯:我想這可能是必要提及的是我的理解是雙不需要的變量。在節目結束時,我也不需要操縱或任何cout。我只是想弄清楚出了什麼問題。 :-)
等於'=='不是'='。修復並重試。 – NathanOliver
打開所有編譯器警告。你可能打算寫'if(grade =='A')'等 –
非常感謝,我不能相信修正那麼簡單。我覺得我好笨。 – DiddyMoe