C ++数组输入和反转值

时间:2017-03-28 17:51:25

标签: c++ arrays

对于一个项目,我需要编写一个程序,该程序读入一系列正整数,存储在一个数组中,以-1结尾。然后它应该颠倒数组的顺序并打印出所有数字的平均值。

ex:输入:21 34 63     输出:63 34 21 Ave:39.3

我不知道从哪里开始。我想可能在while循环中获得用户输入。所以,

int num, i;
const int SIZE = 9;
int arr [SIZE] = {i};
i = 1;
while(num !=-1){
  cout << "Enter a number: ";
  cin >> num;
  arr[i] = num;
  i++;
}
cout << arr; 

好的,首先我如何创建一个接受用户输入并将其作为单独变量存储在数组中的数组? (以上是我对此的不成功尝试。)

2 个答案:

答案 0 :(得分:1)

这是一个简单的问题。您首先需要接受输入然后将其反转。

     int num=0, i,j,k;
        const int SIZE = 99;     //any upperbound value, just to ensure user doesnt enter more values then size of array
        int arr [SIZE] = {0};    //better to initialize with 0
        i = 0;                    //considering 0 indexed
        int sum=0;                 // for average

        while(num !=-1){
          cout << "Enter a number: ";
          cin >> num;
          if(num!=-1)
          {
            arr[i] = num;
            sum+=num;
          } 
          i++;
        }

        int temp;

        //now reversing
        // size of the input array is now i
        for(j=0,k=i-1;j<k;j++,k--)
        {                                
           temp=arr[j];
           arr[j]=arr[k];
           arr[k]=temp;
        }

     //what i am doing here is- keeping the index j on the beginning of the
 //array and k to the end of the array. Then swap the values at j and k, then 
//increase j and decrease k to move to next pair of points. We do this until j is 
//less then k, means until we doesnt reach mid of the array


        //printing the reversed array and average

        cout<<"reversed array"<<endl;

        for(j=0;j<i;j++)
        cout<<arr[j]<<" ";

        cout<<"average"<<float(sum)/i;

查看建议评论

答案 1 :(得分:1)

由于您是用c ++编写程序,因此应该查看std::vectorreverseSTL提供的{{3}}函数。 使用上述工具,您的问题的解决方案如下:

#include <vector>//include to use std::vector
#include <algorithm>//include to use reverse

int main()
{
  std::vector<int> v;                                                           
  int i;                                                                        
  float sum = 0.0f;                                                             
  while(std::cin>>i && i != -1)                                                 
  {                                                                             
    v.push_back(i);                                                             
    sum+=i;                                                                     
  }                                                                             
  reverse(v.begin(),v.end());                                                   
  for(int num : v)                                                              
    std::cout<<num<<" ";                                                        
  std::cout<<"average:"<<sum/v.size()<<std::endl; 
}