在平行数组中重新启动循环
Restart loop in a parallel array
对于我的分配,我不能允许用户在数组中输入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;
}
相关文章:
- WINAPI 注册应用程序重新启动时不清除打开的套接字
- 如何使用 ctypes 停止和重新启动从 Python 运行的C++代码
- 重新启动后,线程无法在 while 循环中再次运行
- 在程序和基于文本的游戏和C++内重新启动程序
- 在程序/基于文本的游戏/C++内重新启动程序
- 为什么使用 exec() 重新启动程序不能正常工作?
- 即使在我关闭应用程序并重新启动它后,如何保持我的 ID 被阻止?
- 有没有办法在不重新启动或注销的情况下加载游标?
- IO服务重新启动后,Boost最后期限计时器持续触发
- 在C++中重新启动随机数序列
- 稍后在构造函数中重新启动异常指令删除此指令
- 如何获取代码::块以在代码::块重新启动后保持库的配置?
- 我想在我设置的几秒钟后重新启动我的程序
- 如何使重新启动此循环,当用户输入 1 时,并在 0 时停止
- UDP 服务器每 5 秒重新启动一次
- 有没有办法检查内存缓存是否已重新启动?
- (Windows 10) 在不更新的情况下重新启动C++
- 在平行数组中重新启动循环
- 如果用户只按Enter或输入无效,则C 如何重新启动循环
- 执行while循环,如果用户选择yes行为不正确,则重新启动程序