首页 > 解决方案 > 如何让用户输入少于 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 个元素。

标签: c++arrayselement

解决方案


您所做的不会阻止他们将大于 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];
    }
}

推荐阅读