题目:
用一维数组接收学生成绩,输出最高成绩学成绩和序号(学生序号从1开始,最后一个是10)。
解题思路:
我们可以在录入数据的同时,让每一个数进行比较,并记录较大值和它的下标。
然后输出结果即可解题(注意下标要进行 + 1)
代码实现:
1.使用指针
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#define SIZE 10
int main()
{
int score[SIZE] = { 0 };
int* p_max = score;//记录最大值地址
int i = 0;
for (i = 0; i < SIZE; i++)
{
scanf("%d", &score[i]);
if ( *p_max < score[i])
{
p_max = &score[i];
}
}
printf("Max of score is %d, which sequence number is %d\n", *p_max, p_max - &score + 1);
return 0;
}
2.使用临时变量
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#define SIZE 10
int main()
{
int score[SIZE] = { 0 };
int max = 0;//记录最大值
int max_index = 0;//追踪最大值的下标
int i = 0;
for (i = 0; i < SIZE; i++)
{
scanf("%d", &score[i]);
if (max < score[i])
{
max = score[i];
max_index = i;
}
}
printf("Max of score is %d, which sequence number is %d\n", max, max_index + 1);
return 0;
}