2013-02-08 31 views
1

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

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

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

+0

这是我在这个网站上看到的最糟糕的标题之一。注意我是如何重写你的头衔的。 –

回答

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; 
} 
+0

好的,谢谢。但是创建第二个功能太快捷。理想情况下,我应该只使用一系列重叠的循环,并且不要使用诸如product = product * x的快捷方式; – user2052971

+0

@ user2052971,像你在前面的评论中所要求的那样的问题难以置信地不可能帮助未来的访问者(因而风险被关闭),仅仅因为唯一的地方你会得到这样的限制是在疯狂的教育者心中。但我会尽全力做到这一点。 – paxdiablo

+0

感谢您的回答和评论,我真的很感激它,但是您错了一件事......我认为了解它的工作原理非常有趣,对我而言这是一个有趣的挑战。显然,我们假设能够进行阶乘甚至是减价,这对我来说似乎很了不起。所以我想有些人不仅希望代码能够工作,还想知道它是如何工作的。再次感谢! – user2052971