在C++Primer 一書中提到一個例子:求解2的10次冪的問題,我第一次寫的代碼如下:
#include<iostream>
int main()
{ //int類型的對象
int val=2;
int pow=10;
cout<<val<<"raised to the power of"
<<pow<<"\t";
int res=1;
//用于保存結(jié)果,
//循環(huán)計算res直至cnt大于pow
for(int cnt=1; cnt<=pow;++cnt)
res=res*val;
cout<<res<<endl;
}
這樣做的程序可移植性差,稱需要拿到別的地方去使用要經(jīng)過較大修改。故考慮修改如下:
首先新建一個函數(shù)如下
int pow(int val,int exp)
{ int res=1;//設(shè)定保存結(jié)果
for(int cnt=1;cnt<=exp;++cnt)
res=res*val;
return res;
}
其次寫一個主程序
#include<iostream>
extern int pow(int,int)
int main()
{
int val=2;
int pow=10;
cout<<val<<"raised to the power of "<<pow<<":\f"
cout<<pow(val,pow)<<endl;
}
后經(jīng)發(fā)現(xiàn)上邊紅色的標(biāo)識的句子,有錯誤應(yīng)改為
for(int cnt=1;exp>=cnt;--exp)
2006年2月8日1:48:05