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

需求:修改C语言阶乘程序,实现重复输入与主动终止功能

支持重复计算的阶乘程序(输入"stop"终止)

修改思路

要实现重复计算直到输入"stop",核心需要解决两个问题:一是能区分用户输入的数字和终止指令,二是循环执行计算流程。具体调整点包括:

  • 改用整行读取输入的方式,同时兼容数字和字符串输入
  • 外层添加无限循环,直到触发终止条件才退出
  • 保留原有的正整数校验逻辑,同时支持在校验过程中输入"stop"退出
  • 每次计算前重置变量,避免上次计算结果干扰

修改后的完整代码

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

int main() {
    char input[50];
    int num, total;

    while (1) {
        printf("Enter integer number (or 'stop' to quit): ");
        // 读取整行输入,处理输入为空或读取失败的情况
        if (fgets(input, sizeof(input), stdin) == NULL) {
            break;
        }

        // 移除输入末尾的换行符,保证字符串比较准确
        input[strcspn(input, "\n")] = '\0';

        // 判断是否触发终止指令
        if (strcmp(input, "stop") == 0) {
            printf("Program terminated.\n");
            break;
        }

        // 尝试将输入转换为整数,校验输入是否为有效数字
        if (sscanf(input, "%d", &num) != 1) {
            printf("Invalid input! Please enter a positive integer or 'stop'.\n");
            continue;
        }

        // 校验输入是否为大于1的正整数,支持中途输入stop退出
        while (num <= 1) {
            printf("Enter any integer number(positive): ");
            fgets(input, sizeof(input), stdin);
            input[strcspn(input, "\n")] = '\0';
            
            if (strcmp(input, "stop") == 0) {
                printf("Program terminated.\n");
                return 0;
            }
            
            if (sscanf(input, "%d", &num) != 1) {
                printf("Invalid input! Please enter a positive integer or 'stop'.\n");
                num = 0; // 重置为0,继续循环提示输入
                continue;
            }
        }

        // 计算阶乘
        total = 1;
        int temp_num = num;
        while (temp_num > 1) {
            total *= temp_num;
            temp_num--;
        }

        printf("total is %d\n", total);
    }

    return 0;
}

关键修改说明

  • 输入处理优化:使用fgets读取整行输入,替代原有的scanf,这样既能接收数字,也能识别"stop"字符串;strcspn函数用于移除输入末尾的换行符,避免字符串比较时出现误差。
  • 循环控制逻辑:外层while(1)实现无限循环,只有当用户输入"stop"时,通过break或return终止程序。
  • 输入校验增强:
    • 先判断输入是否为"stop",触发终止流程;
    • 用sscanf尝试转换输入为整数,失败则提示无效输入;
    • 保留原有的正整数校验循环,同时在该循环中也支持输入"stop"直接退出。
  • 独立计算保证:每次计算阶乘前,重置total和临时变量temp_num,确保每次计算都是独立的,不受上一次计算结果的影响。

内容的提问来源于stack exchange,提问作者Lilkzxl 666

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 23:11:27