1

为了练习的目的,我必须用最基本的算术运算来实现指数函数。我想出了这个,其中x是底数,y是指数:

function expAetB() {
     product=1;
     for (i=0; i<y; i++)
     {
          product=product*x;
     }
     return product;
};

但是,还有比 更多的基本操作product=product*x;。我应该能够以某种方式插入另一个for循环,该循环乘以并传递结果,但是我找不到一种方法来做到这一点而不会陷入无限循环。

4

1 回答 1

2

与求幂是重复乘法一样,乘法只是重复加法。

只需创建另一个为您执行此操作的函数mulAetB,并注意诸如负输入之类的事情。

您甚至可以更上一层楼,并根据增量和减量来定义添加,但这可能有点矫枉过正。


例如,请参阅以下程序,该程序使用加法的过度杀伤方法:

#include <stdio.h>

static unsigned int add (unsigned int a, unsigned int b) {
    unsigned int result = a;
    while (b-- != 0) result++;
    return result;
}

static unsigned int mul (unsigned int a, unsigned int b) {
    unsigned int result = 0;
    while (b-- != 0) result = add (result, a);
    return result;
}

static unsigned int pwr (unsigned int a, unsigned int b) {
    unsigned int result = 1;
    while (b-- != 0) result = mul (result, a);
    return result;
}

int main (void) {
    int test[] = {0,5, 1,9, 2,4, 3,5, 7,2, -1}, *ip = test;
    while (*ip != -1) {
        printf ("%d + %d = %3d\n"  , *ip, *(ip+1), add (*ip, *(ip+1)));
        printf ("%d x %d = %3d\n"  , *ip, *(ip+1), mul (*ip, *(ip+1)));
        printf ("%d ^ %d = %3d\n\n", *ip, *(ip+1), pwr (*ip, *(ip+1)));
        ip += 2;
    }
    return 0;
}

该程序的输出表明计算是正确的:

0 + 5 =   5
0 x 5 =   0
0 ^ 5 =   0

1 + 9 =  10
1 x 9 =   9
1 ^ 9 =   1

2 + 4 =   6
2 x 4 =   8
2 ^ 4 =  16

3 + 5 =   8
3 x 5 =  15
3 ^ 5 = 243

7 + 2 =   9
7 x 2 =  14
7 ^ 2 =  49

如果你真的必须在单个函数中使用它,只需将函数调用重构为内联即可:

static unsigned int pwr (unsigned int a, unsigned int b) {
    unsigned int xres, xa, result = 1;

    // Catch common cases, simplifies rest of function (a>1, b>0)

    if (b == 0) return 1;
    if (a == 0) return 0;
    if (a == 1) return 1;

    // Do power as repeated multiplication.

    result = a;
    while (--b != 0) {
        // Do multiplication as repeated addition.

        xres = result;
        xa = a;
        while (--xa != 0)
            result = result + xres;
    }

    return result;
}
于 2013-02-08T02:36:24.567 回答