繁体   English   中英

当我在 While 循环中使用浮点值时,为什么我的程序会进入无限循环?

[英]Why does my program enter an infinite loop when I use float values in a While loop?

我的任务是做一个程序来读取一个学生的名字,他们的 4 个科目和他们各自的成绩。 我使用过forwhile循环,也使用过if语句,到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main() {
    printf("Este programa captura el nombre de un alumno \n");
    printf  ("y cuatro de sus materias y sus respectivas notas\n");
    printf      ("Nota: El programa solo toma en cuenta los dos primeros\n");
    printf          ("decimales de la notas expresada.\n\n");
    
    char alumno[40] = {'\0'};
    char mat[4][20] = {'\0', '\0', '\0', '\0'};
    float calif[4] = {-1, -1, -1, -1};
    int i;
    
    while (alumno[0] == '\0') {
        printf("Ingresa el nombre del alumno: ");
        gets(alumno);
        if (alumno[0] == '\0') {
            printf("\nError. El alumno debe de llevar un nombre.");
            printf  ("\nTrata nuevamente\n\n");
        };
    };
    for (i = 0; i < 4; ++i) {
        while (mat[i][0] == '\0') {
            printf("Ingresa el nombre de la materia %d: ", i+1);
            gets(mat[i]);
            if (mat[i][0] == '\0') {
                printf("\nError. Las materias deben ser declaradas.");
                printf  ("\nTrata nuevamente.\n\n");
            };
        };
        while (calif[i] < 0 || calif[i] > 10) {
            printf("Ingrese la nota correspondiente a esta materia (0-10): ");
            scanf("%2.2f", calif[i]);
            if (calif[i] < 0 || calif[i] > 10) {
                printf("\nError. Debe ingresar una nota válidad entre 0 y 10.");
                printf  ("\nTrata nuevamente.\n\n");
            };
        };
    };
    
    return 0;
};

该程序似乎运行良好,直到它询问第一门学科的成绩。 我放的任何等级都会导致无限循环。 我已经搜索过这个问题无济于事。 所以请让我知道我在这里做错了什么。

您的代码中有多个问题:

  • [major]你用scanf("%2.2f", calif[i])读取标记:格式字符串不正确,前2表示最多读取 2 个字节,而.2是错误,因为scanf()没有完全支持精确语法。 它应该只是"%f" ,你应该传递目标变量&calif[i]的地址而不是它的值。 此外,您应该测试返回值以检查无效或丢失的输入。

  • main的原型是int main()int main(void)int main(int argc, char *argv[]) ,缺少的返回类型是过时的语法。

  • 使用gets()读取输入是有风险的,因为没有办法防止输入字符串足够长的缓冲区溢出。 您应该改用scanf("%39s", alumno)fgets(alumno, sizeof alumno, stdin)并测试返回值以检测输入 stream 的过早结束。 对于gets()的第二个实例也有同样的评论。

暂无
暂无

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

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