需要帮助来定义循环控制变量(while循环)C ++

时间:2018-07-30 23:55:42

标签: c++

我一直在试图找出要使程序正常工作的循环控制变量(LCV),但我一直没有成功。

给出的信息如下:

您将根据课程的成绩和学分提升学生。由此,您将计算出GPA。

  • 提示输入课程名称,但没有执行任何操作。
  • 我们仅使用A,B,C,D和F级,因此您不必进行太多打字!
  • 您将需要使用本书中所示的“ set precision”命令。将其设置为“固定”和“ 2”。
  • 您将需要使用本课程前面讨论的“ cin.ignore()”函数。

注释

  • 我用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;
}

2 个答案:

答案 0 :(得分:1)

根据程序其余部分的编写方式,我认为您想对照用户对“继续”的响应进行检查。题。像这样:

this

也就是说,使用do-while循环可能更有意义,在该循环中,第一个块在检查条件之前执行:

bool answer = true;
while (answer) {
    // code

    // when ready to exit...
    answer = false;
}

在使用它时,您可能还需要考虑使用与用户输入“是”或“否”不同的标志。像do { // code } while (answer != "No"); y之类的东西更常见,也更简单。

答案 1 :(得分:0)

"while (grade <= "ABC")"

如果意图是仅在等级的值为A,B或C时执行循环,则:

while(grade == "A" || grade == "B" || grade == "C")