马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int numbers[MAX_SIZE];
int counts[201] = {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[i++] = num;
counts[num + 100]++;
}
else
{
printf("整数超出范围\n");
}
}
for (i = 0; i < MAX_SIZE - 1; i++)
{
for (j = 0; j < MAX_SIZE - i - 1; j++)
{
if (counts[j] < counts[j + 1])
{
temp = counts[j];
counts[j] = counts[j + 1];
counts[j + 1] = temp;
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
printf("排序结果:\n");
for (i = 0; i < MAX_SIZE; i++)
{
if (counts[i] != 0)
{
printf("%d出现了%d次\n", numbers[i], counts[i]);
}
}
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[MAX_SIZE];
int counts[201] = {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[i++] = num;
counts[num + 100]++;
}
else
{
printf("整数超出范围\n");
}
}
for (i = 0; i < MAX_SIZE - 1; i++)
{
for (j = 0; j < MAX_SIZE - i - 1; j++)
{
if (counts[j] < counts[j + 1])
{
temp = counts[j];
counts[j] = counts[j + 1];
counts[j + 1] = temp;
temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
printf("排序结果:\n");
for (i = 0; i < MAX_SIZE; i++)
{
if (counts[ i] != 0)
{
printf("%d出现了%d次\n", numbers[ i], counts[ i]);
}
}
return 0;
}
现在代码应该可以正确运行并按照出现次数排序输出结果。
|