为什么不按升序打印数字

Why does this not print the numbers in ascending order

本文关键字:数字 打印 升序 为什么不      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
    int i,sum=0,n;
    int a[10];
    float avg;
        cout<<"Enter how many numbers you want ";
        cin>>n;
        if (n>10)
        n=10;
            cout<<"Enter the numbers" << endl;
                for (i=0;i<n;i++)
                    cin>>a[i];
                for (i=0;i<n;i++)
                    {
                        sum=sum+a[i];
                    }
                        avg=sum/n;
        cout<<"sum of array elements "<<sum << endl;
        cout<<"average of array elements " <<avg << endl;
int temp;
    for (int i =0; i<n; i++)
    {
        for (int j=1; j<n; j++)
        {
            if (a[i] > a[j])
            {
                temp = a[i];
                a[i]=a[j];
                a[j]=temp;  
            }
        }
    }
cout << "The numbers in ascending order are:" << endl;
for (int i =0; i<n; i++)
    {
        cout << a[i] << endl;
    }
return 0;
}

当我运行这个程序时,数字以不同的顺序打印出来。

如果我使用数字 1 2 3 4 5。 他们打印为 1 5 4 3 2。

其他一切正常。 如何修复此错误?

您的排序实现不正确。由于排序的思想是在每一步找到i最小的数字,内部循环应该从 i+1 开始,而不是从 1 开始:

for (int j=i+1; j<n; j++)

演示。