c++實現數值的整數次方(類似pow())作用


/*
 * 計算數值的整數次方.cpp
 *
 *  Created on: 2018年4月13日
 *      Author: soyo
 */
#include<iostream>
#include<math.h>
#include<ctime>
using namespace std;
int main()
{
    double power(double base,int exp);
    int x=2,y=3;
    long int z;
    z=pow(2,3);
    cout<<"值為:"<<z<<endl;
    z=z>>2;//右移兩位
    cout<<"值為:"<<z<<endl;
    double a;
    clock_t start,stop,consume_time;
    start=clock();
    a=power(12,100);
    stop=clock();
    consume_time=stop-start;
    cout<<"新值為:"<<a<<endl;
    cout<<"運行時間為:"<<consume_time<<endl;
}
double power(double base,int exp)
{
    if(exp==0)
        return 1;
    if(exp==1)
        return base;
    double result;
     result=power(base,exp>>1);
     result*=result;
     if(exp&0x1==1)
         result*=base;
//     if(exp%2==1)      //都可以(但第一種效率更高)
//         result*=base;
     return result;
}

結果:

值為:8
值為:2
新值為:8.2818e+107
運行時間為:1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM