C語言求冪計算的高效解法
更新時間:2014年09月18日 09:07:53 投稿:shichen2014
這篇文章主要介紹了C語言求冪計算的高效解法,分別演示了求冪運算與整數(shù)次方的解法,具有不錯的參考借鑒價值,需要的朋友可以參考下
本文實例演示了C語言求冪計算的高效解法。很有實用價值。分享給大家供大家參考。具體方法如下:
題目如下:
給定base,求base的冪exp
只考慮基本功能,不做任何邊界條件的判定,可以得到如下代碼:
#include <iostream> 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; }
再來看看數(shù)值的整數(shù)次方求解方法:
#include <iostream> 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程序算法設(shè)計的學(xué)習(xí)有一定的借鑒價值。
相關(guān)文章
C語言宏定義結(jié)合全局變量的方法實現(xiàn)單片機(jī)串口透傳模式
今天小編就為大家分享一篇關(guān)于C語言宏定義結(jié)合全局變量的方法實現(xiàn)單片機(jī)串口透傳模式,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12C語言詳細(xì)解析有符號數(shù)與無符號數(shù)的表示
我們知道,在C語言中存在無符號數(shù)和有符號數(shù),但是對于計算機(jī)而言,其本身并不區(qū)別有符號數(shù)和無符號數(shù),因為在計算機(jī)里面都是O或者1,但是在我們的實際使用中有時候需要使用有符號數(shù)來表示一個整數(shù),因此我們規(guī)定,當(dāng)最高位為1的時,表示為負(fù)數(shù),最高位為0時,表示為正數(shù)2022-04-04C++ Boost Random隨機(jī)函數(shù)詳解
Boost是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱。Boost庫是一個可移植、提供源代碼的C++庫,作為標(biāo)準(zhǔn)庫的后備,是C++標(biāo)準(zhǔn)化進(jìn)程的開發(fā)引擎之一,是為C++語言標(biāo)準(zhǔn)庫提供擴(kuò)展的一些C++程序庫的總稱2022-11-11