gpt4 book ai didi

c++ - 为什么这不按升序打印数字

转载 作者:行者123 更新时间:2023-11-30 03:54:07 25 4
gpt4 key购买 nike

#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++)

Demo.

关于c++ - 为什么这不按升序打印数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29737731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com