国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C > 正文

C語言求冪計算的高效解法

2020-01-26 15:18:13
字體:
來源:轉載
供稿:網友

本文實例演示了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;}

再來看看數值的整數次方求解方法:

#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程序算法設計的學習有一定的借鑒價值。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 库伦旗| 南汇区| 黎城县| 枣强县| 呼伦贝尔市| 邵东县| 泗水县| 宽甸| 星子县| 晴隆县| 华池县| 赤峰市| 建阳市| 大化| 张家口市| 嘉兴市| 浦县| 宁波市| 菏泽市| 石城县| 河津市| 峨眉山市| 昂仁县| 大同县| 杭州市| 德庆县| 米泉市| 湖口县| 乡城县| 尚义县| 盐城市| 四平市| 克山县| 鸡西市| 尼勒克县| 略阳县| 庆阳市| 五峰| 丹阳市| 安顺市| 泗洪县|