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

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

问题描述

我正在尝试创建一个 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
", sum);
        printf("--------------
");
        --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天全站免登陆