在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