[英]Need help defining a Loop Control Variable (while loops) C++
我一直在努力弄清楚要使用什么循環控制變量(LCV)使我的程序正常工作,但是我一直沒有成功。
給出的信息如下:
您將根據課程的成績和學分提升學生。 由此,您將計算出GPA。
筆記
int total
來計算類的數量。 while
語句是我最后的嘗試,這是不正確的。 我的代碼:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main () {
cout << std::fixed << std::setprecision(2);
string course, grade, answer;
int credits, total = 0;
float gradePoints = 0, totalCredits = 0;
float gpa = 0.0;
while (grade <= "ABC") {
cout << "Enter a course name: ";
getline(cin, course);
cout << course << endl;
cout << "Enter number of credits: ";
cin >> credits;
cout << credits << endl;
cout << "Enter your grade (A, B, C, D, F): ";
cin >> grade;
cout << grade << endl;
cout << "Continue ('Yes' or 'No')? ";
cin >> answer;
cout << answer << endl;
if (grade == "A") {
gradePoints = gradePoints + 4;
}
else if (grade == "B") {
gradePoints == gradePoints + 3;
}
else if (grade == "C") {
gradePoints = gradePoints + 2;
}
else if (grade == "D") {
gradePoints = gradePoints + 1;
}
else if (grade == "F") {
gradePoints = 0;
}
total = total + 1;
totalCredits = totalCredits + credits;
}
gpa = (total * gradePoints)/ totalCredits;
return 0;
}
根據其余程序的編寫方式,我認為您想對照用戶對“繼續”的響應進行檢查。 題。 像這樣:
bool answer = true;
while (answer) {
// code
// when ready to exit...
answer = false;
}
也就是說,使用do-while循環可能更有意義,在該循環中,第一個塊在檢查條件之前執行:
do {
// code
} while (answer != "No");
而且,在使用它時,您可能還需要考慮使用與用戶輸入“是”或“否”不同的標志。 像y
和n
這樣的東西更常見,也更簡單。
"while (grade <= "ABC")"
如果意圖是僅在等級為A或B或C的情況下執行循環,則:
while(grade == "A" || grade == "B" || grade == "C")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.