代码不对
#include <stdio.h>#define MAX_SIZE 100
int main()
{
int numbers;
int counts = {0};
int num, i, j, temp;
printf("请输入整数(以输入-1结束):\n");
i = 0;
while(1)
{
scanf("%d", &num);
if(num == -1)
{
break;
}
if (num >= -100 && num <= 100)
{
numbers = num;
counts++;
}
else
{
printf("整数超出范围\n");
}
}
for (i = 0; i < MAX_SIZE - 1; i++)
{
for (j = 0; j < MAX_SIZE - i - 1; j++)
{
if (counts < counts)
{
temp = counts;
counts = counts;
counts = temp;
temp = numbers;
numbers = numbers;
numbers = temp;
}
}
}
printf("排序结果:\n");
for (i = 0; i < MAX_SIZE; i++)
{
if (counts[ i] != 0)
{
printf("%d出现了%d次\n", numbers[ i], counts[ i]);
}
}
return 0;
}
后面的排序结果运行时根本不显示 问题出在排序的部分。在这段代码中,使用了冒泡排序来对 counts 数组进行排序,但是排序的循环条件有误。
原来的循环条件是 for (i = 0; i < MAX_SIZE - 1; i++) ,这个条件会导致循环只执行了99次,而不是100次。因此,最后一个元素没有被正确排序。
正确的循环条件应该是 for (i = 0; i < MAX_SIZE; i++) ,这样循环就会执行100次,确保所有元素都被正确排序。
以下是修改后的代码:
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int numbers;
int counts = {0};
int num, i, j, temp;
printf("请输入整数(以输入-1结束):\n");
i = 0;
while(1)
{
scanf("%d", &num);
if(num == -1)
{
break;
}
if (num >= -100 && num <= 100)
{
numbers = num;
counts++;
}
else
{
printf("整数超出范围\n");
}
}
for (i = 0; i < MAX_SIZE; i++)
{
for (j = 0; j < MAX_SIZE - i - 1; j++)
{
if (counts < counts)
{
temp = counts;
counts = counts;
counts = temp;
temp = numbers;
numbers = numbers;
numbers = temp;
}
}
}
printf("排序结果:\n");
for (i = 0; i < MAX_SIZE; i++)
{
if (counts[ i] != 0)
{
printf("%d出现了%d次\n", numbers[ i], counts[ i]);
}
}
return 0;
}
现在,排序结果应该能正确地显示出来了。
页:
[1]