如果不满足条件,如何无限期地重做一个动作?
How to redo an action indefinitely if condition is not met?
所以,这是我的代码:
#include <conio.h>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int n;
int a[10];
int main()
{
cout<<"Insert amount of data\n";
cin>>n;
for (int i=0; i < n; i++){
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
if (a[i]<1 || a[i]>3){
cout<<"Please insert only the number 1-3\n";
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
}
}
for (int i=0; i<n;i++) {
cout<<a[i];
}
}
我试图让程序循环直到输入数字 1-3。但是,它没有按照我想要的方式工作。比如我输入5
,它会输出:
Please insert only the number 1-3
Insert number (1, 2, or 3)=
这是正确的。但是,如果我再次输入 5
,它会被输入到数组中。我只希望数组的编号为 1-3。那么,如何使 if 语句循环直到输入数字 1-3?
您已经掌握了使用条件的 for
循环,所以让我们添加一个 do-while-loop
循环
而不是:
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
你可以这样做:
do {
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
} while(a[i] < 1 || a[i] > 3);
您还可以添加错误检查。如果用户关闭输入流,你的程序将永远旋转。
do {
cout<<"Insert number (1, 2, or 3)= ";
if(not (cin>>a[i])) return 1; // failed to read an int, abort the program
} while(a[i] < 1 || a[i] > 3);
所以,这是我的代码:
#include <conio.h>
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int n;
int a[10];
int main()
{
cout<<"Insert amount of data\n";
cin>>n;
for (int i=0; i < n; i++){
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
if (a[i]<1 || a[i]>3){
cout<<"Please insert only the number 1-3\n";
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
}
}
for (int i=0; i<n;i++) {
cout<<a[i];
}
}
我试图让程序循环直到输入数字 1-3。但是,它没有按照我想要的方式工作。比如我输入5
,它会输出:
Please insert only the number 1-3
Insert number (1, 2, or 3)=
这是正确的。但是,如果我再次输入 5
,它会被输入到数组中。我只希望数组的编号为 1-3。那么,如何使 if 语句循环直到输入数字 1-3?
您已经掌握了使用条件的 for
循环,所以让我们添加一个 do-while-loop
循环
而不是:
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
你可以这样做:
do {
cout<<"Insert number (1, 2, or 3)= ";
cin>>a[i];
} while(a[i] < 1 || a[i] > 3);
您还可以添加错误检查。如果用户关闭输入流,你的程序将永远旋转。
do {
cout<<"Insert number (1, 2, or 3)= ";
if(not (cin>>a[i])) return 1; // failed to read an int, abort the program
} while(a[i] < 1 || a[i] > 3);