简体   繁体   English

如何使用递归将两个数字相乘

[英]How to multiply 2 numbers using recursion

I'm trying to multiply (3, 6) and (9, 9) using recursion. 我正在尝试使用递归将(3,6)和(9,9)相乘。 However, the result printed is 18 and 45. I need to find out which part is wrong. 但是,打印的结果是18和45。我需要找出哪一部分是错误的。

Here's my code: 这是我的代码:

#include <stdio.h>

int multiply (int, int);

int main()
{
    int a, b, c;
    a = 6; b = 3; c = multiply(a, b);
    printf("%d\n", c);
    a = 9; b = 9; c = multiply(a, b);
    printf("%d\n", c);
    return 0;
}

int multiply(int a, int b)
{
    static int c = 0, i = 0;
    if (i < a) {
        c = c + b;
        i++;
        multiply(a, b);
    }

    return c;
}

The issue is that multiply 's static variables persist from call to call, which throws the second calculation off. 问题在于, multiplystatic变量在调用之间持续存在,从而导致第二次计算失败。 It is possible to bandage this wound, but it's better to address the underlying design problem that is compelling use of static variables in the first place. 可以包扎此伤口,但是最好解决潜在的设计问题,即首先要使用static变量的问题。 There is no need to artificially maintain state in the function using i (the number of additions to perform) and c (a product accumulator). 无需使用i (要执行的加法数)和c (产品累加器)在功能上人为地维护状态。

Given that multiplication is repeated addition of a b times, you can establish a base case of b == 0 and recursively add a , incrementing or decrementing b (depending on b 's sign) until it reaches 0. The product accumulator c is replaced by the function return value and the number of multiplications i is represented by b . 假设乘法是a b重复加a ,则可以建立b == 0基本情况 ,然后递归加a ,使b递增或递减(取决于b的符号),直到达到0。乘积c被替换由函数返回值和乘数i表示为b

Using this approach, each stack frame's state is naturally self-reliant. 使用这种方法,每个堆栈帧的状态自然都是自相关的。

#include <stdio.h>

int multiply(int a, int b) {
    if (b > 0) {
        return a + multiply(a, b - 1);
    }
    else if (b < 0) {
        return -a + multiply(a, b + 1);
    }

    return 0;
}

int main() {
    printf("%d\n", multiply(3, 6));
    printf("%d\n", multiply(9, 9));
    printf("%d\n", multiply(-6, 2));
    printf("%d\n", multiply(6, -2));
    printf("%d\n", multiply(-7, -3));
    printf("%d\n", multiply(0, 7));
    printf("%d\n", multiply(7, 0));
    printf("%d\n", multiply(0, 0));
    return 0;
}

Output: 输出:

18
81
-12
-12
21
0
0
0

As a final note, I recommend following proper code style. 最后,我建议遵循正确的代码样式。 Minifying your code and using single-character variable names only makes debugging more difficult (someone has since de-minified the original code in an edit). 压缩代码并使用单字符变量名只会使调试更加困难(此后有人在编辑中缩小了原始代码的大小)。

Both c and i need to be reset to zero on each [outer] call to multiply [as others have mentioned] because a function scope static variable is only initialized once . ci需要被复位到零上的每个[外]来电multiply [如其他人提及]因为函数作用域static变量只初始化一次

There is no way to do this because the static variables are at multiply function scope (ie how does main access/reset them?). 因为静态变量在multiply函数作用域内(即主变量如何访问/重置它们),所以无法执行此操作。 They would need to be moved to global/file scope. 它们将需要移至全局/文件范围。

Adding a helper function and moving the variables to global scope will do it: 添加一个辅助函数并将变量移至全局范围将完成此操作:

#include <stdio.h>

int multiply(int, int);

int
main()
{
    int a,
     b,
     c;

    a = 6;
    b = 3;
    c = multiply(a, b);
    printf("%d\n", c);

    a = 9;
    b = 9;
    c = multiply(a, b);
    printf("%d\n", c);

    return 0;
}

static int c, i;

int
mul(int a, int b)
{

    if (i < a) {
        c = c + b;
        i++;
        mul(a, b);
    }

    return c;
}

int
multiply(int a, int b)
{

    i = 0;
    c = 0;

    return mul(a,b);
}

Try resetting your static variables before second call to multiply or do without them 在第二次调用之前尝试重置您的静态变量以进行乘法或不执行它们

int multiply(int a, int b) {
      If (a==0)
           return 1;
      else if (a>0)
           return b+multiply(a-1, b);
        else
          return - 1*multiply(-1*a, b); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM