如何让用户C++输入少于 10 个元素的数组
How do i let the user enter an array less than 10 elements 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 <= 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];
}
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 如何将元素添加到数组的线程安全函数?
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 输出没有重复元素的动态数组(收缩数组)C++
- 数组中最大的非重复元素
- 数组元素打印的递归方法
- 对字符数组中的元素执行逐位操作
- 缓存std::数组的选定元素,并在c++中自动保持其一致性
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 通过交换元素使数组相同
- 按平均值替换数组中的元素
- 打印矢量数组中的所有元素
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 如何为 c++ 的不同变量类型的结构元素创建动态数组?
- 如何将元素从向量转移到新数组?
- 如何在向量数组中插入元素?
- 为什么 2 个相同数组的元素彼此相等
- C++ 中的二维整数数组,每行中的元素数量不均匀