c++ - 如何让用户输入少于 10 个元素的数组 C++
问题描述
我正在尝试获取数组中的最小数字。用户必须输入元素的数量。我想要的最大元素数是 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 <= 10\n";
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];
}
}
推荐阅读
- c# - SQL 如何替换一个值
- python - 使用 python 和请求,如何进行正确的 POST 调用以及在哪里找到标头?
- android - FirebaseAppDistribution:appDistributionUpload gradle 命令中缺少应用程序 ID
- mysql - 跨列和行计算值的实例
- javascript - 使用 redux 钩子时使用 redux 操作的最佳选择是什么?
- sql - Impala 2.11:AnalysisException:选择列表中不支持子查询
- swift - 在 SwiftUI 中获取当前的经纬度
- c++ - 是否可以禁止一个类被动态转换为?
- git - Git - 将发布分支合并到主分支
- tensorflow - 任何想法如何解决激活函数的问题?