阶乘使用加法 [英] Factorial using Addition

查看:129
本文介绍了阶乘使用加法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个找到整数的阶乘的C代码,以便可以将我的代码转换为汇编语言.我的代码似乎将第二个整数相乘"两次.即5 * 4 * 4 * 3 ...我似乎无法找出原因.请帮忙!

I am attempting to create a C code that finds the factorial of a integer so that I may convert my code to assembly language. My code seems to 'multiply' the second integer twice. i.e. 5*4*4*3... I cannot seem to find out why. Help please!

#define N 5

int main() {

    int j = 0;
    int i = 0;

    int num1 = N;
    int num2 = N - 1;
    int sum = 0;

    while (num2 != 0) {
        while (j < num2) {
            sum += num1;
            j++;
        }
        j = 0;
        printf("%d\n", sum);
        printf("--------------\n");
        --num2;
        num1 = sum;
    }
    printf("--->%d", sum);
}

错误输出:

20
--------------
80
--------------
240
--------------
480
--------------
480

推荐答案

这是机器状态,从中可以看到为什么算法不正确的原因:

Here's the machine state, from which you should be able to see why your algorithm isn't right:

PS思考这一问题的另一种也许更好的方法是您的数学是错误的.您正在执行三个乘法(内部循环的重复-使用重复加法乘以一个整数).但是您还要添加三个产品.这些总和告诉您您不是在计算阶乘.

PS Another, perhaps better, way to think about this is that your mathematics is wrong. You're doing three multiplications (repetitions of the inner loop--multiplying by an integer using repeated addition). But you also do three additions of the products. Those sums tell you that you're not computing a factorial.

这篇关于阶乘使用加法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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