[英]Incorrect return of a function in C
I am trying to write a program to compute the GPA of some grades.我正在尝试编写一个程序来计算某些成绩的 GPA。 The idea is to learn how to use functions in C.
这个想法是学习如何使用 C 中的函数。 The following grades correspond to the following numerical values: A = 4, B = 3, C = 2, D = 1 & F= 0.
以下等级对应以下数值:A = 4、B = 3、C = 2、D = 1 & F= 0。
When inputting the grades in the grades[]
array our function should be case insensitive.在 Grades
grades[]
数组中输入成绩时,我们的 function 应该不区分大小写。 Here is my code:这是我的代码:
#include <stdio.h>
#include <ctype.h>
float compute_GPA(char grades[], int n);
int main(void)
{
int n;
printf("Type length of the array: ");
scanf("%d", &n);
char grades[n];
printf("Type in the (%d) grades you wish to enter: ", n);
for(int i = 0; i < n; i++) {
scanf("%c", &grades[i]);
}
printf("The average value is %f\n", compute_GPA(grades, n));
return 0;
}
float compute_GPA(char grades[], int n)
{
int sum = 0;
float average;
for(int i = 0; i < n; i++) {
if('a' <= grades[i] && grades[i] <= 'f')
grades[i] = toupper(grades[i]);
switch(grades[i]) {
case 'A': sum += 4; break;
case 'B': sum += 3; break;
case 'C': sum += 2; break;
case 'D': sum += 1; break;
case 'F': break;
}
}
average = (float) sum / n;
return average;
}
After staring at it for a while I can't understand why the arithmetic is wrong.盯着它看了一会儿,我不明白为什么算术是错误的。 If, say, I let
n = 3
and type in AB C
for the grades for some reason my answer comes out as 1.3333333
instead of 3.00000
.例如,如果我让
n = 3
并输入AB C
出于某种原因我的答案是1.3333333
而不是3.00000
。 Likewise it won't let me enter an array of length 1. There is something off and I don't know what it is and it is really bugging me.同样,它不会让我输入长度为 1 的数组。有一些东西,我不知道它是什么,它真的让我很烦。 Any help would be appreciated.
任何帮助,将不胜感激。
You should use scanf(" %c", &grades[i]);
你应该使用
scanf(" %c", &grades[i]);
(add space before %c
) instead of scanf("%c", &grades[i]);
(在
%c
之前添加空格)而不是scanf("%c", &grades[i]);
to have scanf()
skip whitespace characters.让
scanf()
跳过空白字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.