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

标签 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

我正在尝试弄清楚如何使其复制输入的数字,但是我被困在为第一个作业编写的下面的代码上,并且我知道可以使用循环来使其变得更短但我只有大约一周的 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);
}

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

最佳答案

您可以使用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);

现在,当您获得总和后,您就可以计算平均值了。年级等。

附注请注意,这里不欢迎诸如“修复我的代码”之类的问题。我知道学习 C 语言的第一步并不容易。阅读一些基础教程,运行其中的示例代码。并尝试将您的问题提出得更具体。

关于c - 我应该在我的 C 代码中修复什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40120280/

相关文章:

仅使用按位操作将 float 转换为 int (float2int)

python - 在 C 中用另一个函数名称批量替换函数名称

c - 嵌入式系统 Linux 中 RAM 使用率最低的情况

c - 如何在 C 中正确显示 groupID (GID)?

c - FreeType2 26.6 尺寸转换为像素转换器

c - 在 Mac OS X 上用 C 操作剪贴板

c - pjsip 显示零往返时间 (RTT)

c - gcc 是否提供内置函数来读取大端内存?

c - 如何处理 c 中的 196,608 个 if 语句?

c++ - 行排序数据到列排序数据的最快转换