在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;
//用于保存結果,
//循環計算res直至cnt大于pow
for(int cnt=1; cnt<=pow;++cnt)
res=res*val;
cout<<res<<endl;
}
這樣做的程序可移植性差,稱需要拿到別的地方去使用要經過較大修改。故考慮修改如下:
首先新建一個函數如下
int pow(int val,int exp)
{ int res=1;//設定保存結果
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;
}
后經發現上邊紅色的標識的句子,有錯誤應改為
for(int cnt=1;exp>=cnt;--exp)
2006年2月8日1:48:05