C++ C++;数组输入和反转值
对于一个项目,我需要编写一个程序,读入一系列正整数,存储在一个数组中,以-1结尾。然后它应该反转数组的顺序,并将其与所有数字的平均值一起打印 例:输入:21 34 63 产出:63 34 21大街:39.3 我不知道从哪里开始。我想也许在一个while循环中得到一个用户输入。所以C++ C++;数组输入和反转值,c++,arrays,C++,Arrays,对于一个项目,我需要编写一个程序,读入一系列正整数,存储在一个数组中,以-1结尾。然后它应该反转数组的顺序,并将其与所有数字的平均值一起打印 例:输入:21 34 63 产出:63 34 21大街:39.3 我不知道从哪里开始。我想也许在一个while循环中得到一个用户输入。所以 int num, i; const int SIZE = 9; int arr [SIZE] = {i}; i = 1; while(num !=-1){ cout << "Enter a number
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;
int-num,i;
常数int SIZE=9;
int arr[SIZE]={i};
i=1;
while(num!=-1){
cout>num;
arr[i]=num;
i++;
}
这是一个简单的问题。您首先需要获取输入,然后将其反转。
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;
int num=0,i,j,k;
常数int SIZE=99//任何上限值,只是为了确保用户输入的值不会超过数组的大小
int arr[SIZE]={0}//最好使用0初始化
i=0//考虑0索引
整数和=0;//平均而言
while(num!=-1){
cout>num;
如果(num!=-1)
{
arr[i]=num;
sum+=num;
}
i++;
}
内部温度;
//现在逆转
//输入数组的大小现在是i
对于(j=0,k= i-1;j),因为您正在C++中编写程序,所以应该查看和提供给您的函数。
使用上述工具,您的问题的解决方案如下:
#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;
}
#include//include使用std::vector
#include//include使用反向
int main()
{
std::向量v;
int i;
浮动总和=0.0f;
而(std::cin>>i&&i!=-1)
{
v、 推回(i);
总和+=i;
}
反向(v.begin(),v.end());
for(int num:v)
我想你应该考虑一下这些输入是如何存储的。我猜是一个数组。然后,下一步是如何反转给定的数组。int arr[SIZE]如果用户输入的不是代码>大小>代码>项目,那么将是一个问题。……你的问题到底是什么?提示:反向洛芬特++:反向循环并求所有值,然后将它划分成数组。SiZeI认为用户是C++的新成员,必须尝试简单的方法。UR解决方案更接近于OP请求的答案,但我会把它放在这里,因为有人可能会发现它有用。当然,对于其他用户来说,这肯定是有用的。他只需要输出数组和反向数组,他不必在内存中反转它。使用temp.ya我知道,但数组的大小不是固定的。这看起来是一个好的开始,但它计算的平均值是错误的,因为它也将0加上,然后除以包括0在内的数字量。我想我可以解决这个问题。谢谢。@RinionValvan这不是问题。问题是sum和i都是整数o它正在将浮点结果转换为整数(数据丢失)。已修复