【问题标题】:Incorrect return of a function in CC中函数的错误返回
【发布时间】:2021-04-25 12:50:51
【问题描述】:

我正在尝试编写一个程序来计算某些年级的 GPA。想法是学习如何使用C中的函数。以下等级对应于以下数值:A = 4,B = 3,C = 2,D = 1 & F= 0。

grades[] 数组中输入成绩时,我们的函数应该不区分大小写。这是我的代码:

#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;
}

看了一会儿,我不明白为什么算术是错误的。例如,如果我让n = 3 输入A B C 作为成绩,出于某种原因,我的答案是1.3333333 而不是3.00000。同样,它不会让我输入长度为 1 的数组。有一些东西,我不知道它是什么,它真的让我很烦。任何帮助将不胜感激。

【问题讨论】:

  • 您可能正在阅读一些\n 而不是成绩。
  • 你说得对。
  • 一些快速调试应该可以帮助您解决这个问题。每日一课:如果您的程序似乎没有按照您的预期运行,请始终使用调试器单步执行它,同时监控变量及其值。
  • 另请注意sum / n 不会按预期工作。 sumint,以及 n。因此它将是 int devision,只有在之后结果才会转换为 float。结果将始终向下舍入...
  • 我已经使用了一个演员来把它变成一个浮动。这不解决问题吗?

标签: arrays c function


【解决方案1】:

您应该使用scanf(" %c", &amp;grades[i]);(在%c 之前添加空格)而不是scanf("%c", &amp;grades[i]); 以使scanf() 跳过空白字符。

【讨论】:

    猜你喜欢
    • 2014-03-25
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2016-04-13
    • 1970-01-01
    相关资源
    最近更新 更多