运行不对
#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 != 0)
{
printf("%d出现了%d次\n", numbers, counts);
}
}
return 0;
}
这代码运行起来不对 这段代码的问题在于排序部分的循环条件有误。循环条件应为 i < MAX_SIZE - 1 ,而不是 i < MAX_SIZE 。因为数组 numbers 和 counts 的大小都是 MAX_SIZE ,所以循环条件应该是 i < MAX_SIZE - 1 ,以避免访问数组越界。
以下是修改后的代码:
#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;
}
现在代码应该可以正确运行并按照出现次数排序输出结果。
页:
[1]