程序里开了一个数组写试试桶排序
但是我没输入100这个数,为什么会输出100,而且有时输出很多
#include<iostream>
using namespace std;
int main()
{
int a[100]={0},n;
for(int c=0;c<10;c++)
{
cin>>n;
a[n]++;
}
for(int i=0;i<=100;i++)
{
for(int j=0;j<a[i];j++)
{
cout<<i<<endl;
}
}
return 0;
}
这是一次输出结果
23
23
24
34
1
2
3
3
34
32
1
2
3
3
23
23
24
32
34
34
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
--------------------------------
Process exited after 11.64 seconds with return value 0
请按任意键继续. . .23
23
24
34
1
2
3
3
34
32
1
2
3
3
23
23
24
32
34
34
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
--------------------------------
Process exited after 11.64 seconds with return value 0
请按任意键继续. . .
数组下标从0开始,所以int a[100]的最后一个元素是a[99]
#include<iostream>
using namespace std;
int main()
{
int a[100]={0},n;
for(int c=0;c<10;c++)
{
cin>>n;
a[n]++;
}
for(int i=0;i<100;i++)//i<=100改为i<100
{
for(int j=0;j<a[i];j++)
{
cout<<i<<endl;
}
}
return 0;
}
应该是数组越界了,第11行循环执行了101次,访问了a[100],而a[100]的值是不确定的。