C語言求冪計(jì)算的高效解法
本文實(shí)例演示了C語言求冪計(jì)算的高效解法。很有實(shí)用價(jià)值。分享給大家供大家參考。具體方法如下:
題目如下:
給定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; }
相信本文所述對(duì)大家C程序算法設(shè)計(jì)的學(xué)習(xí)有一定的借鑒價(jià)值。
相關(guān)文章
C語言實(shí)現(xiàn)字母大小寫轉(zhuǎn)換的方法
這篇文章主要介紹了C語言實(shí)現(xiàn)字母大小寫轉(zhuǎn)換的方法,涉及C語言字符串的遍歷與轉(zhuǎn)換技巧,非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下2015-07-07

C語言實(shí)現(xiàn)簡(jiǎn)單的貪吃蛇游戲

C語言詳細(xì)解析有符號(hào)數(shù)與無符號(hào)數(shù)的表示

C++ Boost Random隨機(jī)函數(shù)詳解