循环不工作时执行

Do while Loops not working

本文关键字:执行 工作 循环      更新时间:2023-10-16

我一直在循环使用一项作业,以在课堂上进一步练习和发展我的编程技能,但我在另一个DO WHILE循环中遇到了3个DO WHILE循环的问题。

我试图否认测试1、2和3的测试分数小于1且大于100。我遇到循环没有处理我为Test1/2/3输入的内容。它允许while范围之外的值通过。有没有人能建议或看到我可能做错了什么?提前感谢各位!

    #include<iostream>
    #include<cmath>
    #include<iomanip>
    using namespace std;
    double computeavg (int a, int b, int c);
    char lettergrade (double z);
    int main ()
    {

    double test1, test2, test3, average; //test1/2/3, test scores, Average:         average of test scores
    double tottest1=0, tottest2=0, tottest3=0, avg1, avg2, avg3; //tottest# - sum of test grades collected for that number test, avg# average for first         second or third test
    int student=0, avgvar; //average variable, Student number
    char grade, ans; // Holds a letter grade, holds a response to a question
    do{
    student=student+1;
        cout<<"Hello Student #"<<student<<endl;
        do{
        cout<<"Please input test 1 Grade ";
            cin>> test1;
        }   
        while(test1>=1||test1<=100);
        do{
        cout<<"Please input test 2 Grade ";
            cin>> test2;
        }   
        while(test2>=1||test2<=100);
        do{
        cout<<"Please input test 3 Grade ";
            cin>> test3;
    }
        while(test3>=1||test3<=100);        
    average=computeavg (test1, test2, test3);
        cout<<setprecision(0)<<fixed;
        cout<<"Your Average is: "<<average<<endl;
    tottest1=tottest1+test1;
    tottest2=tottest2+test2;
    tottest3=tottest3+test3;
    grade = lettergrade(average);
        cout << "Your grade is " << grade << endl;
            cout<<"Do you want to grade another student? (y/n)";
            cin>>ans;
        cout<<"n";
    } while(ans=='y');

我认为您需要更改do while,如下所示:

do{

    cout<<"Please input test 1 Grade ";
        cin>> test1;
    }   
    while(test1<1||test1>100);

您的条件是落后的。仔细看:while(test3>=1||test3<=100)所有数字至少满足部分条件。例如,减号;4不大于或等于1,但小于或等于100,并且由于您的条件与||运算符(即运算符)连接,因此条件计算结果为true。

你需要改变条件。这是家庭作业,所以我不会确切地告诉你应该使用什么条件。

您可以使用调试器自行发现此问题。你也可以通过仔细地用手浏览你的程序来发现它。拿一支铅笔和一些纸,写下变量的当前值。跟踪你正在使用的指令,然后按照自己的方式完成程序。当一个变量发生变化时,划掉它的旧值,记下新值。最终,你将能够在脑海中做到这一点,但在你学习的同时,把它写下来会有所帮助。