gpt4 book ai didi

c - 是代码块错误吗?

转载 作者:行者123 更新时间:2023-11-30 16:49:38 25 4
gpt4 key购买 nike

我有一项作业要求我对随机数进行排序。下面的代码很奇怪。原因是点击运行程序后,如果我在开头输入5,它不能完美运行,但是,它可以与其他数字正常运行。请帮我修复这个错误。我还附上了图片来证明我上面所说的。

Image when enter number 5

Image when enter number 10

#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]);


}


}

最佳答案

问题是因为您正在读取和打印的数据比数组的实际大小小一。因此数组的最后一项将具有一些您不知道的垃圾值。但是在排序时你正在使用它并且它会被排序。有时,垃圾值低于其他随机值,并且会被打印出来。

我已经修复了。请检查所有 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]);


}


}

关于c - 是代码块错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42503512/

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