无法获取阶乘函数在C工作 [英] Unable to get a factorial function to work in C

查看:94
本文介绍了无法获取阶乘函数在C工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能让下面的code工作。

I cannot get the following code to work.

#include <stdio.h>

// I am not sure whethere I should void here or not.
int main() {
    // when the first bug is solved, I put here arg[0]. It should be
    // similar command line parameter as args[0] in Java.
    int a=3;                  
    int b; 
    b = factorial(a);

    // bug seems to be here, since the %1i seems to work only in fprintf
    printf("%1i", b);
    return 0;      
}  

int factorial(int x) {
    int i; 
    for(i=1; i<x; i++) 
        x *= i; 
    return x; 
}

你怎么能得到code的工作?

推荐答案

AInitak 给了正确的答案,但我想补充一点,一个你的方式可以的找到的在code中的错误是打印出的值我 X 中的阶乘循环。

AInitak gave the right answer, but I want to add that one way you can find the bug in your code is to print out the values of i and x in the factorial loop.

int factorial(int x) {
    int i;
    for(i=1; i<x; i++)
    {
        x *= i;
        printf("%d, %d\n", i, x);
    }
    return x;
}

这让你的输出

1, 3
2, 6
3, 18
4, 72
5, 360
6, 2160
7, 15120
8, 120960
9, 1088640
10, 10886400
11, 119750400
12, 1437004800
13, 1501193216
14, -458131456
-458131456

这使得它更容易看到什么错。循环不停止,你指望它为AInitak解释的原因。

This makes it easier to see what's going wrong. The loop doesn't stop where you expect it to for the reasons AInitak explained.

这篇关于无法获取阶乘函数在C工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆