如何退出while循环? C ++

时间:2019-09-27 06:44:08

标签: c++ while-loop

好,在有人anyone我之前,我检查了每个论坛来尝试帮助我解决此问题,但不幸的是无法解决。有人可以指出正确的方向来解决这个问题吗?我试图在输入值-1时立即退出do while循环。例如,当我输入-1时,我希望输出看起来像这样:

输入预期的充电小时数: //用户输入-1 正在退出...

#include <iostream>
#include<iomanip>
using namespace std;

int main() {

    float hour;
    float Network1, Network2, Network3;

    do {
        cout << "Enter the expected number of hours charging:" << endl;
        cin >> hour;

    Network1= (1 * hour) + 10;
    Network2= (2.50 * hour);
    Network3 = (0.50 * hour) + 20;

        cout << "Your expected costs are: " << endl;
        cout << "Network 1: $" << fixed << setprecision(2) << Network1 << endl;
        cout << "Network 2: $" << fixed << setprecision(2) << Network2 << endl;
        cout << "Network 3: $" << fixed << setprecision(2) << Network3 << endl;

        if(Network1 < Network2 && Network1 < Network3){
            cout << "The lowest cost network is $" << Network1 << endl;
        }
        else if (Network2 < Network1 && Network2 < Network3){
            cout << "The lowest cost network is $" << Network2 << endl;
        }
        else{
            cout << "The lowest cost network is $" << Network3 << endl;
        }
    }
    while (hour != -1) ;

    cout << "Exiting..." << endl;

    return 0;
    }

2 个答案:

答案 0 :(得分:2)

有两种方法:

  1. 您可以在阅读后立即检查输入内容
cin >> hour;
if (hour == -1) {
    break;
}
  1. 您可以使用while循环并读取两次值。第一次迭代之前的第一个,最后一次迭代的第二个
cout << "Enter the expected number of hours charging:" << endl;
cin >> hour;
while (hour != -1) {
    // ...
    cout << "Enter one more value:" << endl;
    cin >> hour;
}

答案 1 :(得分:0)

执行此操作的基本方法有两种,尼安德特人方式和深红色者方式。

穴居人的方式;

for(;;) { 
   cout << "Enter the expected number of hours charging:" << endl;
   cin >> hour;
   if (!cin || hour == -1) break;
   ...

深红色的方式:

while (std::cout << "Enter the expected number of hours charging: \n" &&
            std::cin >> hour &&
            hour! = -1) {
   ...

不涉及对cin进行正确检查的方法属于pithcanthrops。