简体   繁体   中英

While loop and cin

The code below should ask the user his weight and if the user puts > 15 it should do a while loop to increase it to 50 The code compiles successfully but no matter if you put > 15 it wont do the while loop.

#include <iostream>
using namespace std;

int main()
{


int weight;

cout << "Current weight?" << endl;
cin >> weight;
cout << "Your weight:" << weight << endl;
if (weight > 15) {
        while (weight == 50) {
            weight = weight + 1;
            cout << "Weight:" << weight << endl;
        }
}
return 0;
}
while(weight==50){
    weight = weight +1;
    cout <<"Weight:"<<weight<<endl;
}

The above loop will keep on going as long as weight is equal to 50 which, by judging from what you have written in the question, is not what you are looking for.

To fix the problem, change the loop-condition into something more suitable; didn't you want to keep on looping as long as weight is less-than 50 ?

只要给定条件为真,C / C ++编程语言中的while循环语句就会重复执行目标语句。

weight ==50 condition will fail if you enter weight value other than fifty. To do what you have mentioned modify condition in while loop.

weight == 50

to

weight < 50

If you ran this program step-by-step, using a debugger, and you added watches of the values of variables, you would see what's going on.

Your development environment (what you use to write code) likely has an integrated debugger; alternatively, use another dev. env.'s debugger, or a stand-alone debugger like gdb for the command line, kdbg for KDE, ddd for any X environment etc. (those are all on Linux; other platforms may have other debuggers).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM