对于我的分配,我不能允许用户在数组中输入rainfall
的负值。我想再次重新启动循环,好像他们没有输入任何要开始的东西,然后让他们重试。
尝试它时,我第一次输入一个负值,它将在一月份重新启动,但是在此之后,我可以输入更多的负面值,它只是要求我继续进入剩下的几个月。如果我继续给出负数,我希望它继续重新启动,直到开始进入正数为止。然后,那是我显示总和平均的时候。
{
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;
}
}
这是您要完成的工作的基本工作示例。与其添加然后检查,我先检查了值,然后将值添加到数组中。我创建了一个简单的功能,以确保输入是有效的数字。如果不是这样,只需将计数器重置回0即可从头开始。
编辑:添加尝试和捕获块以确保输入是正确的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";
}
好吧,那是您陷入困境的时循环,当您第二次放置负值时,您已经在循环时,因此不会打印对不起....而不是从循环中重新启动。计数器= 0,宁愿这样做
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;
}