我应该在C代码中修复什么?

时间:2016-10-19 00:44:03

标签: c

我想首先说我不是要求答案,但是我想就语法中应该寻找的内容提出一些建议。这是我最初的几个C作业之一。我的代码有如下所示的输出。

How many grade items would you like to enter?   4

Enter the grade for grade item number 1: 67
Enter the grade for grade item number 2: 79.4
Enter the grade for grade item number 3: 90
Enter the grade for grade item number 4: 83.5

Average grade: 79.97%
Letter grade: C

我正在试图弄清楚如何让它复制输入的数字然而我却停留在我为第一个作业编写的下面的代码中我明白循环本来可以用来使这个更短但我只有大约一周的使用经验。

#include <stdio.h>

int main() {
   int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, sum, total = 1200;
   float per;

   printf("\nEnter the score for Assignment 1: "); // Assignment statements
   scanf("%d", &a1);
   printf("\nEnter the score for Assignment 2: ");
   scanf("%d", &a2);   
   printf("\nEnter the score for Assignment 3: ");
   scanf("%d", &a3);   
   printf("\nEnter the score for Assignment 4: ");
   scanf("%d", &a4);
   printf("\nEnter the score for Assignment 5: ");
   scanf("%d", &a5);   
   printf("\nEnter the score for Assignment 6: ");
   scanf("%d", &a6);      
   printf("\nEnter the score for Assignment 7: ");
   scanf("%d", &a7);
   printf("\nEnter the score for Assignment 8: ");
   scanf("%d", &a8);   
   printf("\nEnter the score for Assignment 9: ");
   scanf("%d", &a9);   
   printf("\nEnter the score for Assignment 10: ");
   scanf("%d", &a10);
   printf("\nEnter the score for Assignment 11: ");
   scanf("%d", &a11);   
   printf("\nEnter the score for Assignment 12: ");
   scanf("%d", &a12);       

   sum = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12;

   per = (sum * 100) / total;
   printf("\nPercentage : %f", per);

    return (0);
}

任何建议都很棒(或链接到我应该检查的内容?),在简单的打印/扫描声明后我感到非常困惑。

3 个答案:

答案 0 :(得分:1)

您可以使用for循环输入多个值:

int a, sum = 0;
int n;
printf("\nHow many grade items would you like to enter? ");
scanf("%d", &n);
int i;
for (i = 1; i <= n; ++i) {
    printf("\nEnter the score for Assignment %d: ", i);
    scanf("%d", &a);
    sum = sum + a;
}
printf("\nsum: %d", sum);

现在,当你得到总和时,你就可以计算出平均值。等级等。

P.S。请注意像&#34;修复我的代码&#34;等问题。在这里不受欢迎。我知道学习C的第一步并不容易。阅读一些基本教程,从中运行示例代码。并尝试更具体地解决您的问题。

答案 1 :(得分:1)

所以我在帮助你,因为我知道新手的感觉。首先是代码流:

  1. 取一个整数来相应地获得主题数(arr[])和数组(for)。
  2. 现在开始针对总主题(0 to n-1)重复arr[i] = marks循环。
  3. 现在输入用户的值并将它们存储在数组((totalMarks = totalMarks + marks))中,并在变量(totalMarks)中同时添加主题的值以获得总标记totalMarks。 OR
  4. 如果您不想打印它们,请直接将主题添加到变量(totalMarks)。
  5. 最后将总变量(n*100)除以总变量(per = (totalMarks)/(n*100))并将其乘以100并将其存储在每个中。

    {{1}}

  6. 这是该计划的流程。

    希望这有帮助。

答案 2 :(得分:0)

一个好的方法是检查要为扫描值指定的变量的数据类型(int,float等)。 看一下&#34;格式说明符&#34;。 至于显示最终成绩的要求,您可能想学习如何使用条件语句。

看到你的经验相对较少,我还不建议进行更多的优化。

开始使用C的一个很好的资源是Learning C the Hard Way,它可以处理你当前遇到的所有问题。

相关问题