快速提问。我和我的"而且"环

时间:2016-07-07 09:18:39

标签: c++ loops while-loop exit

我遇到了烦人的问题。我遇到的问题是;当我在第一个cin >> statement中输入-1时,while不会像我想要的那样退出。

我试图不在循环中使用"break",因为我已经被告知这是一个坏习惯。

FYI moveOn初始化为true。 这是代码:

while(moveOn){

cout << "Enter info:";
cin >> weight;
if(weight == -1){
    moveOn = false;
}

weight = pack.weight;
cin >> pack.sides[0] >> pack.sides[1] >> pack.sides[2];

    while(pack.weight > 0 || pack.sides[0] < 0 || pack.sides[1] < 0 || pack.sides[2] < 0){
        cout << "Enter Vaild info:";
        cin >> pack.weight >> pack.sides[0] >> pack.sides[1] >> pack.sides[2];
    }

girth = getGirth(pack.sides);
float price;
price = getPackageAmount(pack.weight, weights, prices);
cout << price << endl;

if( pack.weight <= 50){
    if(pack.sides[0] <= 36 && pack.sides[1] <= 36 && pack.sides[2] <= 36){
        if(girth <= 60){
            pack.accepted = true;
            accepted++;
        }
    }
}
else{
    pack.accepted = false;
    rejected++;

}
}

提前谢谢。

1 个答案:

答案 0 :(得分:3)

while(moveOn)并不意味着&#34;当moveOn成为false&#34; - 测试仅在循环的每次迭代开始时执行。

您需要添加else子句:

while (moveOn)
{
    cout << "Enter info:";
    cin >> weight;
    if(weight == -1){
        moveOn = false;
    }
    else
    {
        weight = pack.weight;
        // ...
    }
}

(您可能还想将weight = pack.weight更改为pack.weight = weight。)