题目
编写程序,从键盘上输入N个学生的考试成绩存入一维数组中,求该数组中成绩的最高分、最低分及平均分并输出到屏幕。
解题步骤
(1)定义常量N值;
(2)建立用于存放数据的一维数组;
(3)接收用户输入;
(4)查询 / 计算特定值;
(5)输出结果;
Java
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
final int N = 10;
float[] array = new float[N];
float Max, Min, Average = 0;
System.out.println("please enter the " + N + " students test results in order:");
for (int i = 0; i < N; i++) {
array[i] = input.nextFloat();
}
Max = Min = array[0];
for (int i = 0; i < N; i++) {
if (array[i] > Max)
Max = array[i];
if (array[i] < Min)
Min = array[i];
Average += array[i];
}
Average /= N;
System.out.format("highest score:%.1f,lowest score:%.1f,the average score:%.2f",Max,Min,Average);
}
}
说明
注意Java中接收用户输入的方法,同时考虑对一维数组“动态赋值”的操作。
C语言
#include <stdio.h>
#define N 10
int main()
{
float array[N], Max,Min,Average;
printf("please enter the N students test results in order:");
for (int i = 0; i < N; i++)
{
scanf("%f", &array[i]);
}
Max =Min=array[0];
for (int i = 0; i < N; i++)
{
if (array[i] > Max)
Max = array[i];
else if (array[i] < Min)
Min = array[i];
Average += array[i];
}
Average /= N;
printf("highest score:%.1f,lowest score:%.1f,the average score:%.3f", Max, Min, Average);
return 0;
}
说明
==
scanf()
中别丢弃
&
取地址符== (异常:输入数据后无输出)。求平均值无需增加变量
Sum
,可将变量
Average
放入循环体内求总和,在循环体外进行平均值求算。