以相同的方式,指数是重复的乘法,所以乘法就是简单的重复加法。
简单地创建另一个函数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;
}
这是我在这个网站上看到的最糟糕的标题之一。注意我是如何重写你的头衔的。 –