我有一项任务要求我对随机数进行排序。下面的代码很奇怪。原因是在单击运行程序后,如果我在开头键入5,它不能完美地工作,但是,它可以与其他数字一起正常工作。请帮我修复此错误。我还附上照片来证明我上面所说的。
#include <stdio.h>
int main(){
int howmany,i,temp,swap;
printf("Enter how many numbers you want to sort: \n");
scanf(" %d",&howmany);
int number[howmany];
printf("*** The original numbers *** \n");
for (i=0;i<howmany-1 ;i++){
number[i]=(rand()% 25)+1;
printf("Random number is: %d\n",number[i]);
}
while(1){
swap = 0;
for (i=0;i<howmany-1;i++){
if(number[i]>number[i+1]){
temp = number[i];
number[i]=number[i+1];
number[i+1] = temp;
swap = 1;
}
}
if (swap == 0){
break;
}
}
printf("*** The sorted numbers ***\n");
for (i=0;i<howmany-1;i++){
printf("The sorted number: %d\n",number[i]);
}
}
答案 0 :(得分:0)
问题是因为您正在阅读和打印的数量少于数组的实际大小。所以数组的最后一个条目会有一些你不知道的垃圾值。但是在排序时你正在使用它并且它被排序。有时垃圾值低于其他随机值并打印出来。
我做了修复。请检查所有for循环。
#include <stdio.h>
int main(){
int howmany,i,temp,swap;
printf("Enter how many numbers you want to sort: \n");
scanf(" %d",&howmany);
int number[howmany];
printf("*** The original numbers *** \n");
for (i=0;i<howmany ;i++){ //Read howmany values and print
number[i]=(rand()% 25)+1;
printf("Random number is: %d\n",number[i]);
}
while(1){
swap = 0;
for (i=0;i<howmany-1;i++){
if(number[i]>number[i+1]){
temp = number[i];
number[i]=number[i+1];
number[i+1] = temp;
swap = 1;
}
}
if (swap == 0){
break;
}
}
printf("*** The sorted numbers ***\n");
for (i=0;i<howmany;i++){ //Print howmany values
printf("The sorted number: %d\n",number[i]);
}
}