计算平均程序时输出错误

丹妮拉(Daniela Morais)

多年来,我没有做用C任何事情,我现在不能做简单的事情,我已经习惯了cincout现在的Java。我试图编写一个简单的程序来计算平均X笔考试笔记数量。输出为“随机数”,在输入音符之前进行检查以中断程序。这是为什么?

#include <stdio.h>

int main(void) {
    int numeroDeNotas;
    float nota = 0.0;
    float notaAuxiliar = 0.0;
    char continuar;
    int media;

    do{
    printf("Enter the exam grade\n");
    scanf("%f", &notaAuxiliar);
    nota += (int) notaAuxiliar;
    numeroDeNotas++;
    printf("Do you want to continue? Enter n if you want to stop\n");
    scanf("%c", &continuar);
    }while(continuar != 'n');

    printf("%d\n\n", nota);
    printf("%d\n\n", numeroDeNotas);

    media = nota/numeroDeNotas;
    printf("Average grade: %d", media);
    return 0;
}

notafloat,但是您正在使用%d格式代码进行打印。%d期望一个int; 您需要%f打印浮点数。

C的标准I / O格式绝对不是类型安全的。提供格式代码时,必须确保相应的参数具有正确的类型。但是,如果您使用该-Wall选项进行编译(至少使用gccclang进行编译),则编译器会发出警告。

同样,scanf("%c", &continuar);读取单个字符而不跳过空格,空格将是紧接在读取的数字之后的字符scanf("%f", &notaAuxiliar);该字符很可能是换行符。在阅读y之前,您需要跳过空格n,因此可以使用:

scanf(" %c", &continuar);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章