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

C语言求输入值内奇数阶乘代码出错:5以上结果异常求助

Fixing the Odd Factorial Calculation Error

Hey there! I spot the exact issue causing your wrong results after calculating 5's factorial—let's walk through it and fix things up.

The Root Problem

Your result variable is only set to 1 once at the very start of the program. When you compute 3's factorial, result ends up as 6. Then, when you move on to calculate 5's factorial, you don't reset result back to 1—instead, you multiply that existing 6 by 12345, giving you 720 instead of the correct 120 (5! = 120). That's why your numbers go off the rails after 5.

The Simple Fix

Move the result = 1; line inside the outer for loop. This way, every time you start calculating the factorial of a new odd number, result starts fresh from 1 instead of carrying over the previous calculation's value.

Here's the corrected code:

#include <stdio.h>
int main() {
    int input;
    printf("Enter the integer number : ");
    scanf("%d", &input);
    printf("n:!\n\n");
    for(int i = 1; i <= input; i = i + 2) {
        int result = 1; // Reset result for each new odd number
        for(int k = 1; k <= i; k++) {
            result *= k;
        }
        printf("%d:%d\n", i, result);
    }
    return 0;
}

Quick Verification

If you run this fixed code and input 5, you'll get the correct output:

Enter the integer number : 5
n:!

1:1
3:6
5:120

Perfect—those are the accurate factorials for 1, 3, and 5.

内容的提问来源于stack exchange,提问作者Jung Jae Won

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 08:12:53