如何让用户C++输入少于 10 个元素的数组

How do i let the user enter an array less than 10 elements C++

本文关键字:元素 数组 用户 C++ 输入      更新时间:2023-10-16

>我正在尝试获取数组中的最小数字。用户必须输入元素的数量。我想要的最大元素数是 10。

我尝试编写一个if条件,但我认为我做得不对。

int main(){
int x, e;
int arr[10];        
cout << "Enter number of elements(1 to 10)" << endl;
cin >> e;
for(x = 0; x < e; x++){
cout << "Enter number" << x+1 << " : " << endl;
cin >> arr[x];
if (arr[x] > 10){
cout << "Try entering a number <= 10";
}

我希望如果用户输入多个大于 10 的元素,它将打印"Try entering a number",但用户可以输入大于 10 的元素,然后它只会接受前 10 个元素。

您正在执行的操作不会阻止他们将大于 10 的数字添加到数组中,因为您仍在将数字添加到数组中。 你想要类似的东西


int main(){
int x, e;
int arr[10];
cout<< "Enter number of elements(1 to 10)"<<endl;
cin>>e;
for(x = 0; x < e; x++){
cout<<"Enter number"<< x+1<< " : "<<endl;
cin>>arr[x];
while(arr[x] > 10){
cout<<"Try entering a number <= 10n";
cin>>arr[x];
}
}
}

但是,这将阻止他们向数组中添加大于 10 的数字。我相信你想要的是防止他们使 e 大于 10。为此,您可以做这样的事情。


int main(){
int x, e;
int arr[10];
cout<< "Enter number of elements(1 to 10)"<<endl;
cin>>e;
while(e > 10)
{
cout<< "Enter number of elements(1 to 10)"<<endl;
cin>>e;
}
for(x = 0; x < e; x++){
cout<<"Enter number"<< x+1<< " : "<<endl;
cin>>arr[x];
}
}