c语言求幂 编程,C语言求幂计算的高效解法

本文介绍了C语言中计算幂的两种高效方法,包括位运算优化的循环求幂和递归求幂,适用于基本的幂计算,不涉及边界条件处理。通过示例代码展示如何实现,并提供了一个浮点数求幂的完整函数`myPow`,考虑了负指数的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文实例演示了C语言求幂计算的高效解法。很有实用价值。分享给大家供大家参考。具体方法如下:

题目如下:

给定base,求base的幂exp

只考虑基本功能,不做任何边界条件的判定,可以得到如下代码:

#include

using namespace std;

int cacExp(int base, int exp)

{

int result = 1;

int theBase = 1;

while (exp)

{

if (exp & 0x01)

result = result * base;

base = base * base;

exp = exp >> 1;

}

return result;

}

int getRecurExp(int base, int exp)

{

if (exp == 0)

{

return 1;

}

if (exp == 1)

{

return base;

}

int result = getRecurExp(base, exp >> 1);

result *= result;

if (exp & 0x01)

result *= base;

return result;

}

int main()

{

for (int i = 1; i < 10; i++)

{

int result = cacExp(2, i);

//int result = getRecurExp(2, i);

cout << "result: " << result << endl;

}

return 0;

}

再来看看数值的整数次方求解方法:

#include

using namespace std;

bool equalZero(double number)

{

if (number < 0.000001 && number > -0.000001)

return true;

else

return false;

}

double _myPow(double base, int exp)

{

if (exp == 0)

return 1;

if (exp == 1)

return base;

double result = _myPow(base, exp >> 1);

result *= result;

if (exp & 0x01)

result *= base;

return result;

}

double _myPow2(double base, int exp)

{

if (exp == 0)

return 1;

double result = 1;

while (exp)

{

if (exp & 0x01)

result *= base;

base *= base;

exp = exp >> 1;

}

return result;

}

double myPow(double base, int exp)

{

if (equalZero(base))

return 0;

if (exp == 0)

return 1;

bool flag = false;

if (exp < 0)

{

flag = true;

exp = -exp;

}

double result = _myPow2(base, exp);

if (flag)

{

result = 1 / result;

}

return result;

}

void main()

{

double base = 2.0;

int exp = -5;

double result = myPow(base, exp);

cout << "result: " << result << endl;

}

相信本文所述对大家C程序算法设计的学习有一定的借鉴价值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值