请问为什么数字顺序无法调换呢?

img

img


//设置数组,完成相应任务
#include
#include
using namespace std;
int main()
{
const int N=15;//N为数据数
double a[N+1];//a[N+1]为数组
//任务1
cout<<"请输入15个实型数:"<<endl;//12.3 34.5 64.5 23.7 1.23 78.9 50.4 88.2 34.7 5.6 90.3 24.3 78.67 44.5 6.5
int i;
for(i=0;i<N;i++)
cin>>a[i];//输入数组元素的值
for(i=0;i<N;i++)
{
cout<<right<<setw(10)<<a[i];//输出数组元素
if((i+1)%5==0)
cout<<endl;
}
//任务2
double sum=0,average;
for(i=0;i<N;i++)
sum=sum+a[i];
average=sum/N;
a[N]=average;
//任务3
cout<<"调整后的数据为:"<<endl;
int j=N-1;
double temp;
while(i<j)
{
if(a[i]<average&&a[j]>=average)
{ temp=a[i];
a[i]=a[j];
a[j]=temp;
i++;
j--;
}
else if(a[i]>=average)
i++;
else if(a[j]<average)
j--;
else
{ i++;
j--;}
}
//任务4
for(i=0;i<N+1;i++)
{
cout<<right<<setw(10)<<a[i];
if((i+1)%5==0)
cout<<endl;
}
cout<<endl;
return 0;
}

a[N]=average; 任务2里面你直接平均值给了a[N],那a[N]原本的数据就没有了呀

修改处见注释,供参考:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    const int N = 15;//N为数据数
    double a[N + 1];//a[N+1]为数组
    //任务1
    cout << "请输入15个实型数:" << endl;//12.3 34.5 64.5 23.7 1.23 78.9 50.4 88.2 34.7 5.6 90.3 24.3 78.67 44.5 6.5
    int i;
    for (i = 0; i < N; i++)
        cin >> a[i];//输入数组元素的值
    for (i = 0; i < N; i++)
    {
        cout << right << setw(10) << a[i];//输出数组元素
        if ((i + 1) % 5 == 0)
            cout << endl;
    }
    //任务2
    double sum = 0, average;
    for (i = 0; i < N; i++)
        sum = sum + a[i];
    average = sum / N;
    a[N] = average;
    //任务3
    cout << "调整后的数据为:" << endl;
    int j = N - 1;
    double temp;
    i = 0;              //修改
    while (i < j)
    {
        if (a[i] < average && a[j] >= average)
        {
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
        else if (a[i] >= average)
            i++;
        else if (a[j] < average)
            j--;
        //else       //修改
        //{          //修改
        //    i++;     //修改
        //    j--;     //修改
        //}          //修改
    }
    //任务4
    for (i = 0; i < N + 1; i++)
    {
        cout << right << setw(10) << a[i];
        if ((i + 1) % 5 == 0)
            cout << endl;
    }
    cout << endl;
    return 0;
}