慕容7483954
2021-09-15 22:32
#include<stdio.h>
void rank1(int arr[])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10; j++)
{
int max;
if (arr[j + 1] > arr[j])
{
max = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = max;
}
}
}
for (int m = 0; m < 10; m++)
{
printf("%d,", arr[m]);
}
printf("\n");
}
void rank2(int arr[])
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10; j++)
{
int min;
if (arr[j + 1] < arr[j])
{
min = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = min;
}
}
}
for (int m = 0; m < 10; m++)
{
printf("%d,", arr[m]);
}
printf("\n");
}
int sumandavr(int arr[])
{
int i = 0;
double a = 0;
for (int j = 0; j < 10; j++)
{
i += arr[j];
}
printf("\n总和为%d", i);
a = i / 10;
printf("\n平均为%lf", a);
return 0;
}
int best(int arr[])
{
int m = arr[0];
for (int i = 0; i < 9; i++)
{
if (arr[i + 1] > m)
{
m = arr[i + 1];
}
}
printf("\n最好的成绩为%d", m);
return 0;
}
int worst(int arr[])
{
int m = arr[0];
for (int i = 0; i < 9; i++)
{
if (arr[i + 1] < m)
{
m = arr[i + 1];
}
}
printf("\n最差的成绩为%d", m);
return 0;
}
int main()
{
int score[10] = { 67,98,75,63,82,79,81,91,66,84 };
rank1(score);
rank2(score);
sumandavr(score);
best(score);
worst(score);
return 0;
}
我这样报错了,求教
在rank1()和rank2()中进行j循环比较时,应该让j<9,而不是j<10。若j<10,则当j=9时继续进入循环,比较arr[9]和arr[10],而arr[10]xia下标越界,具体修改后代码如下所示:
#include<stdio.h>
void rank1(int arr[]) //降序
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
int max;
if (arr[j + 1] > arr[j])
{
max = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = max;
}
}
}
for (int m = 0; m < 10; m++)
{
printf("%d,", arr[m]);
}
printf("\n");
}
void rank2(int arr[]) //升序
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
int min;
if (arr[j + 1] < arr[j])
{
min = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = min;
}
}
}
for (int m = 0; m < 10; m++)
{
printf("%d,", arr[m]);
}
printf("\n");
}
int sumandavr(int arr[])
{
int i = 0;
double a = 0;
for (int j = 0; j < 10; j++)
{
i += arr[j];
}
printf("\n总和为%d", i);
a = i / 10;
printf("\n平均为%lf", a);
return 0;
}
int best(int arr[])
{
int m = arr[0];
for (int i = 0; i < 9; i++)
{
if (arr[i + 1] > m)
{
m = arr[i + 1];
}
}
printf("\n最好的成绩为%d", m);
return 0;
}
int worst(int arr[])
{
int m = arr[0];
for (int i = 0; i < 9; i++)
{
if (arr[i + 1] < m)
{
m = arr[i + 1];
}
}
printf("\n最差的成绩为%d", m);
return 0;
}
int main()
{
int score[10] = {67,98,75,63,82,79,81,91,66,84};
rank1(score);
rank2(score);
sumandavr(score);
best(score);
worst(score);
return 0;
}
C语言入门
926026 学习 · 20793 问题
相似问题