storm-2006

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

关于求解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 on 2006-02-08 01:50 岩石 阅读(622) 评论(1)  编辑 收藏 引用

评论

# re: 关于求解2的10次幂的程序设计 2006-05-28 18:09 beyonlin

//使用函数库
#include<cmath>
pow(2,10);  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2006年5月>
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

导航

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论