我正在编写一个代码,告诉用户输入 100 到 200 之间的不确定数量的数字。该程序告诉我唯一数字的数量,然后对估算的数字进行排序。这是我的代码:
#include <stdio.h>
void sort(int *numbers, int count) {
for (int m = 0; m < count; m++) {
for (int j = 0; j < count - m - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
void printA(int *numbers, int count) {
for (int i = 0; i < count; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
}
int main() {
int numbers[101] = {0}; // using an array to keep track of numbers between 100 and 200
int input, count = 0;
printf("Enter numbers between 100 and 200 (enter a number outside this range to finish):\n");
while (1) {
scanf("%d", &input);
if (input < 100 || input > 200) {
break;
}
if (numbers[input - 100] == 0) {
count++;
numbers[input - 100] = input;
}
}
printf("\nTotal unique numbers entered: %d\n", count);
sort(numbers, count);
printA(numbers, count);
return 0;
}
程序告诉我正确输入的唯一数字的数量,但无法对它们进行排序。有人可以告诉我我做错了什么吗?
OP代码中最重要的问题是
printA
和sort
以count
作为参数调用,然后将其用作函数内的数组大小。但是,count
正在计算输入的数字数量,而不是 numbers
数组的大小。
numbers
数组保存按数字顺序输入的所有唯一数字,因此无需排序,只需排除 0 条目(对应于未输入的范围内的数字)。
最后,应检查
scanf()
的返回码以验证是否确实收到了新号码。
总而言之,代码可以调整如下:
#include <stdio.h>
void printA(int *numbers, int size) {
for (int i = 0; i < size; i++) {
if(numbers[i]) printf("%d ", numbers[i]);
}
printf("\n");
}
int main() {
int numbers[101] = {0}; // using an array to keep track of numbers between 100 and 200
int input, count = 0;
printf("Enter numbers between 100 and 200 (enter a number outside this range to finish):\n");
while (1) {
if(scanf("%d", &input) != 1)
{
printf("Invalid input\n");
scanf("%*[^\n]%*c"); // Remove invalid input from buffer
continue;
}
if (input < 100 || input > 200) {
break;
}
if (numbers[input - 100] == 0) {
count++;
numbers[input - 100] = input;
}
}
printf("\nTotal unique numbers entered: %d\n", count);
printA(numbers, sizeof(numbers)/sizeof(numbers[0]));
return 0;
}