我必须按升序对数组中三个用户输入的数字进行排序。有几个错误。
A)我将它设置为只询问三个数字,但我必须输入4,即使程序只对前三个进行排序。
B)我收到一个警告,说我的变量temp未被使用,即使它显然是。
C)程序对前两个数字进行排序,然后再次打印第二个最高数字而不是最大数字。
以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
int main(){
int numbers = 3;
int NUM_ARRAY[numbers];
int counter = 0;
int sort = 0;
int temp = 0;
printf("Please enter three integers\n");
for(counter = 0; counter < numbers; counter++){
scanf("%d ", &NUM_ARRAY[counter]);
}
printf("Original Numbers\n");
for(counter = 0; counter < numbers; counter++){
printf("%d\n", NUM_ARRAY[counter]);
}
while(1){
sort = 0;
for(counter = 0; counter < numbers-1; counter++){
if(NUM_ARRAY[counter] > NUM_ARRAY[counter+1]){
int temp = NUM_ARRAY[counter];
NUM_ARRAY[counter] = NUM_ARRAY[counter+1];
NUM_ARRAY[counter+1] = NUM_ARRAY[counter];
sort = 1;
}
}
if(sort == 0){
break;
}
}
printf("Sorted Numbers\n");
for(counter = 0; counter < numbers; counter++){
printf("%d\n", NUM_ARRAY[counter]);
}
return 0;
}
答案 0 :(得分:1)
您应将temp设置为NUM_ARRAY[counter+1]
而不是NUM_ARRAY[counter]
试试这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
int main(){
int numbers = 3;
int NUM_ARRAY[numbers];
int counter = 0;
int sort = 0;
int temp = 0;
printf("Please enter three integers\n");
for(counter = 0; counter < numbers; counter++){
scanf(" %d", &NUM_ARRAY[counter]); // changed spacing on %d
}
printf("Original Numbers\n");
for(counter = 0; counter < numbers; counter++){
printf("%d\n", NUM_ARRAY[counter]);
}
while(1){
sort = 0;
for(counter = 0; counter < numbers-1; counter++){
if(NUM_ARRAY[counter] > NUM_ARRAY[counter+1]){
int temp = NUM_ARRAY[counter];
NUM_ARRAY[counter] = NUM_ARRAY[counter+1];
NUM_ARRAY[counter+1] = temp; <--- /* Since NUM_ARRAY[counter] will be set to next value in the previous step */
sort = 1;
}
}
if(sort == 0){
break;
}
}
printf("Sorted Numbers\n");
for(counter = 0; counter < numbers; counter++){
printf("%d\n", NUM_ARRAY[counter]);
}
return 0;
}