首页 > 文章列表 > 在C程序中,编写自己的幂运算函数,但不能使用乘法(*)和除法(/)操作符

在C程序中,编写自己的幂运算函数,但不能使用乘法(*)和除法(/)操作符

自定义函数 C程序 幂运算
218 2023-08-19

幂函数是使用乘法运算符进行计算的,即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