You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中for循环无限重复无法终止问题求助

循环无法终止的问题分析与修复

你的代码核心问题是缓冲区溢出,导致循环变量被意外篡改,进而让循环无法正常结束。

问题根源

  1. 错误的格式符使用:
    • classx是单个char类型变量,但你用scanf("%s", &classx)读取课程名。%s是字符串读取格式符,会将输入内容(比如CS101)加上字符串终止符\0写入内存,而classx仅占1字节空间,多余的数据会溢出到相邻的变量内存区域(比如循环变量i或count),直接破坏循环的控制条件。
    • 读取成绩时的scanf("%s", &grade)也存在同样问题,grade是单个char,用%s读取会引发缓冲区溢出。

修正后的代码

#include <stdio.h>

int main()
{   
    double honorpoints, totalhp = 0, totalcredits = 0;
    int crpassed = 0, clpassed = 0, count;
    float GPA, credits;
    char classx[20], grade; // 定义字符数组存储课程名
    printf("How many classes did you take in the semester: ");
    scanf("%d", &count);
    getchar(); // 清除输入count后的换行符,避免干扰后续字符读取

    for(int i = 0; i < count; i++)
    { 
        printf("Enter a Class: \n");
        scanf("%19s", classx); // 限制读取长度,防止缓冲区溢出
        printf("Enter the number of credits: ");
        scanf("%f", &credits);
        totalcredits += credits;
        getchar(); // 清除输入credits后的换行符

        printf("Enter your grade: ");
        scanf("%c", &grade); // 用%c读取单个字符
        getchar(); // 清除输入grade后的换行符

        honorpoints = 0;
        if (grade == 'A' || grade == 'a')
        {
            honorpoints = credits * 4;
            crpassed += credits;
            clpassed += 1;
        }
        else if (grade == 'B' || grade == 'b')
        {
            honorpoints = 3 * credits;
            crpassed += credits;
            clpassed += 1;
        }
        else if (grade == 'C' || grade == 'c')
        {
            honorpoints = 2 * credits;
            crpassed += credits;
            clpassed += 1;
        }
        else if (grade == 'D' || grade == 'd')
        {
            honorpoints = 1 * credits;
            crpassed += credits;
            clpassed += 1;
        }
        totalhp += honorpoints;
    }

    // 计算并输出GPA及相关统计
    GPA = totalhp / totalcredits;
    printf("\nYour GPA: %.2f\n", GPA);
    printf("Total passed credits: %d\n", crpassed);
    printf("Total passed classes: %d\n", clpassed);
    return 0;
}

关键修正点

  • 将char classx改为char classx[20],用字符数组存储课程名,同时用%19s限制读取长度,预留1字节给字符串终止符\0,彻底避免缓冲区溢出。
  • 读取成绩时改用%c格式符,匹配单个char类型的grade变量。
  • 在每次读取数字后调用getchar(),清除缓冲区中残留的换行符,防止后续%c读取到换行符而非用户输入的成绩字符。
  • 增加大小写兼容逻辑,支持输入小写字母的成绩。
  • 补充GPA计算和结果输出,让程序功能完整。

内容的提问来源于stack exchange,提问作者Sierra Walker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:45:37