storm-2006

真诚和理解是人与人交往中最珍贵的赠品

2006年2月8日

关于求解2的10次幂的程序设计

在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

posted @ 2006-02-08 01:50 岩石 阅读(625) | 评论 (1)编辑 收藏

仅列出标题  
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论