重新启动并行数组中的循环

时间:2019-02-22 07:01:08

标签: c++ loops

对于我的分配,我不允许用户在数组中为rainfall输入一个负值。我想重新开始循环,就好像他们没有输入任何内容开始并让他们重试一样。

当我尝试输入时,我第一次输入负值,它将在1月重新启动,但是之后我可以输入更多的负值,并且一直要求我在接下来的几个月中继续输入。如果我一直给它一个负数,我希望它继续重启,直到我开始输入正数为止。然后,这就是我显示的总数和平均值。

{
    const int SIZE = 12;
    string months[SIZE] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

    string Month[SIZE];
    double Rainfall[SIZE];
    int counter;

    double totalRainfall = 0.0;

    double averageRainfall = 0.0;

    for (counter = 0; counter < SIZE; counter++)
    {
        cout << "Enter the total rainfall for " << months[counter] << ": ";
        cin >> Rainfall[counter];

        if (Rainfall[counter] < 0.0)
        {
            cout << "Sorry, can't be a negative!" << endl;
            do
            {
                for (counter = 0; counter < SIZE; counter++)
                {
                    cout << "Enter the total rainfall for " << months[counter] << ": ";
                    cin >> Rainfall[counter];
                }
            } while (Rainfall[counter] < 0.0);
        }

        averageRainfall = totalRainfall / SIZE;
        cout << "Total rainfall for the whole year was: " << totalRainfall << setprecision(3) << endl;
        cout << "The average inches of rainfall was: " << averageRainfall << setprecision(3) << endl;

        system("pause");
        return 0;
    }
}

2 个答案:

答案 0 :(得分:0)

这就是您困住的while循环,当您第二次输入负值时,您已经在while循环中,因此不会打印对不起...。相反,它将从counter = 0重新开始while循环, 宁愿这样做

if (Rainfall[counter] < 0.0)
    {
        cout << "Sorry, can't be a negative!" << endl;
        counter--;// either put zero if you want to restart whole loop else decrement
        continue;
    }

答案 1 :(得分:0)

这是您要完成的工作的基本示例。在将值添加到数组中之前,我先进行了检查,而不是添加然后检查。我创建了一个简单的函数来确保输入的数字有效。如果不是,只需将计数器重置为0,for循环将从头开始。

编辑:添加一个try and catch块以确保输入是正确的double

#include <iostream>
#include <string>

bool is_valid_num(std::string str){

    //check if its a number
    for(char c : str){
        if((c < 48 || c > 57 ) && c != 46) return false;
    }

    //if you want it to also not be equal to 0
    // if(std::stoi(str) < 0) return false;

    return true;
}

int main() {

    const int SIZE = 12;
    std::string months[] = { "January", "February", "March", "April", "May", "June", 
                        "July", "August", "September", "October", "November", "December" };


    std::string temp_input;
    double rainfall[12]; 
    double total_rainfall = 0.0;

    for(int i = 0; i < SIZE; i++){

        std::cout << "enter rainfall for " << months[i] << ": ";
        std::cin >> temp_input;

        //restart back to january
        if(!(is_valid_num(temp_input))) i = -1;

        rainfall[i] = std::stod(temp_input);
        total_rainfall += std::stod(temp_input);

    }

    std::cout << "avg rainfall: " << total_rainfall / 12.0 << "\n";
    std::cout << "total rainfall " << total_rainfall << "\n";
}