gpt4 book ai didi

c++ - 输出是垃圾值

转载 作者:行者123 更新时间:2023-11-28 01:14:18 24 4
gpt4 key购买 nike

这是我的代码。有什么不对吗?这个项目是关于降序排序的,我确实在网上查了一些示例代码,但它和我的差不多。但是我的代码总是打印垃圾值内存。

#include <iostream>
using namespace std;

void input(int a[], int n)
{
for( int i=0;i<n;i++)
{
cin>>a[i];
}
}
void sort(int a[], int n)
{
int i; int j; int temp;
for (i=0;i<n-1;i++)

for( j=i+1;i<n;j++)
{
if(a[i]<a[j])
{
temp =a[i];
a[i]=a[j];
a[j]=temp;
}

}

}
int output(int a[], int n)
{
for ( int i=0;i<n;i++)
{
cout<<a[i]<<' ';
}

}

int main()
{
int n;
cin>>n;
int a[n];
input(a,n);
sort(a,n);
output(a,n);
return 0;
}

最佳答案

请更改i<nj<n在排序函数中的内部 for 循环上。它可能会有所帮助:)

#include <iostream>
using namespace std;

void input(int a[], int n)
{
for( int i=0;i<n;i++)
{
cin>>a[i];
}
}
void sort(int a[], int n)
{
int i; int j; int temp;
for (i=0;i<n;i++)

for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
temp =a[i];
a[i]=a[j];
a[j]=temp;
}

}

}
int output(int a[], int n)
{
for ( int i=0;i<n;i++)
{
cout<<a[i]<<' ';
}

}

int main()
{
int n;
cin>>n;
int a[n];
input(a,n);

sort(a,n);
output(a,n);
return 0;
}

现在如果你想要第二个最大值,你可以从a[n-2]得到.

关于c++ - 输出是垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59196151/

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