以相同的方式,指數是重複的乘法,所以乘法就是簡單的重複加法。
簡單地創建另一個函數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;
}
這是我在這個網站上看到的最糟糕的標題之一。注意我是如何重寫你的頭銜的。 –