简体   繁体   English

用C创建成绩簿程序

[英]Creating a gradebook program in C

I'm working on a program that will keep track of grades entered. 我正在开发一个程序,该程序可以跟踪输入的成绩。 The program should ask if the user is finished inputting grades. 程序应询问用户是否完成了成绩输入。 If the the user is not finished, the user will continue to enter grades. 如果用户尚未完成,则用户将继续输入成绩。 If the user is finished, program will print the grades. 如果用户完成操作,程序将打印成绩。 Every time I run the program, it crashes. 每次我运行该程序时,它都会崩溃。

Here's what I got. 这就是我得到的。

#include <stdio.h>

int main (){
    int i = 0;
    float gradeBook;
    char ans, y, Y, n, N;

    printf("Please enter grade %d: ", i + 1);
    scanf("%.2f", &gradeBook);

    printf("\nDo you have more grades to enter? [Y or N] ");
    scanf("%c", ans);

    while(ans == 'y' || ans == 'Y'){
        printf("Please enter the next grade %d: ", i + 1);
        scanf("%i", &gradeBook);

        printf("\nDo you have more grades to enter? ");
        scanf("%c", ans);
    }
    printf("You have entered %d grades", i);
    printf("The grades you have entered are %.2f ", gradeBook);
    return 0;
}

You should use arrays for problems like this. 您应该将数组用于此类问题。 Here is what I did: 这是我所做的:

#include <stdio.h>

int main (){
int i = 0, j;
float gradeBook[20];
char ans;

printf("Please enter grade %d: ", i + 1);
scanf("%f", &gradeBook[0]);

printf("\nDo you have more grades to enter? [Y or N] \n");
scanf(" %c", &ans);

while (ans == 'y' || ans == 'Y') {
printf("Please enter the next grade: \n");
i += 1;
scanf("%f", &gradeBook[i]);

printf("\nDo you have more grades to enter? \n");
scanf(" %c", &ans);
}

printf("You have entered %d grades\n", i+1);
printf("The grades you have entered are: \n");
for (j=0; j<=i; j++)
printf("%.2f ", gradeBook[j]);

printf("\n\n");

return 0;
}

Your program crashes because you are missing the & in ans in your scanf. 由于您在scanf中缺少&,因此程序崩溃。 Without the &, the scanf treats the value in "ans" as an address, and will try to access it, thus seg fault. 如果不使用&,scanf会将“ ans”中的值视为地址,并将尝试访问它,从而导致段错误。

PS: In each iteration you are overwriting the value in "gradeBook", if you want to print a set of values, you should use an array. PS:在每次迭代中,您都将覆盖“ gradeBook”中的值,如果要打印一组值,则应使用数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM