使用循环处理数组:输入十个高尔夫成绩,求总分,平均分,差点(平均分与标准分的差值)
为什么数组读取十个数要输入十一个数?
原因:
scanf是格式化输入语句,接收字符"%d "中有一个空格,所以你输入的每一个数字应该是(数字+空格)的格式,才能被接收,最后你输入第十个没结束循环,是因为还没有输入空格,你可以直接把"%d "中的空格去掉("%d"),接收的数字默认以空格分割。
#include<stdio.h>
#define SIZE 10
#define PAR 72
int main(){
int index,score[SIZE];
int sum = 0;
float average;
printf("Enter %d golf scores:\n",SIZE);
for(index=0; index < SIZE; index++)
scanf("%d ",&score[index]); //输入十一个数读取前十个
/*
scanf("%d",&score[index]);
输入十个读取十个
*/
printf("The scores read in are as follows:\n");
for(index = 0; index < SIZE; index++)
printf("%5d",score[index]);
printf("\n");
for(index = 0; index < SIZE; index++)
sum += score[index];
average = (float) sum / SIZE;
printf("SUM of scores = %d, average = %.2f, handicap is %.2f",sum,average,average-PAR);
return 0;
}