幂函数是使用乘法运算符进行计算的,即5n等于5*5*5… n次。为了使该函数在不使用乘法(*)和除法(/)运算符的情况下正常工作,我们将使用嵌套循环来重复添加数字n次。
示例#include <iostream>using namespace std;int main() { int a= 4 , b = 2; if (b == 0) cout<<"the answer is"<<1; int answer = a; int increment = a; int i, j; for(i = 1; i < b; i++) { for(j = 1; j < a; j++) { answer += increment; } increment = answer; } cout<<"the answer is "<<answer; return 0;}
输出the answer is 16
以上就是在c程序中,编写自己的幂运算函数,但不能使用乘法(*)和除法(/)操作符的详细内容。