多年来,我没有做用C任何事情,我现在不能做简单的事情,我已经习惯了cin
和cout
现在的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", ¬aAuxiliar);
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;
}
nota
是float
,但是您正在使用%d
格式代码进行打印。%d
期望一个int
; 您需要%f
打印浮点数。
C的标准I / O格式绝对不是类型安全的。提供格式代码时,必须确保相应的参数具有正确的类型。但是,如果您使用该-Wall
选项进行编译(至少使用gcc
或clang
进行编译),则编译器会发出警告。
同样,scanf("%c", &continuar);
读取单个字符而不跳过空格,空格将是紧接在读取的数字之后的字符scanf("%f", ¬aAuxiliar);
。该字符很可能是换行符。在阅读y
或之前,您需要跳过空格n
,因此可以使用:
scanf(" %c", &continuar);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句