自己實現pow(double base, unsigned exponent)

來源:互聯網
上載者:User

題目來自劍指Offer,描述:

實現函數double pow(double base, unsigned exponent)

這裡有幾個注意點:

1. exponent有可能為正為負

2. 當base 為0,exponent為負數時,此時結果數學上並沒有定義

3. 數學公式的使用: 

          a^(n/2)*a^(n/2)        n為偶數

a^n = a^((n-1)/2)*a^((n-1)/2) *a  n為奇數

具體代碼如下:

#include <iostream>#include <cstdio>using namespace std;bool valid_input = false;    //根據該值判斷輸入是否有效bool equal(double num1, double num2)    //判斷兩個值是否相等{if(num1-num2>-1e-6&& num1-num2<1e-6)return true;return false;}//////////////////////////////////////      a^(n/2)*a^(n/2)     n為偶數//a^n =  //a^(n/2)*a^(n/2)*a   n為奇數//////////////////////////////////double pow_with_unsigned(double base, unsigned int exponent){if(exponent == 0)   //任何數的0次冪都為1return 1;if(exponent == 1)return base;double result = pow_with_unsigned(base, exponent>>1);  result *= result;if(exponent & 0x01 == 1)//指數為奇數result *= base;return result;}double pow(double base, int exponent){valid_input = false;if(equal(base, 0.0) && exponent<0)  //當底數為0,其冪為負數時,指定輸入無效,其返回0(1也可以,代表輸入有誤){valid_input = true;return 0.0;//底數為0,且指數小於0,返回0.0,並標誌輸入無效}unsigned int abs_exponent = (unsigned int)exponent;if(exponent<0)abs_exponent = (unsigned int)(-exponent);double result = pow_with_unsigned(base, abs_exponent);if(exponent < 0)               //指數小於0,求結果的倒數result = 1.0/result;return result;}int main(void){double rel = pow(0, -3);cout << rel << endl;return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.