返回   cpper编程论坛 > Zion/测试
注册账号 论坛帮助 会员列表 日历事件 搜索 今日新帖 标记版面已读

Zion/测试 惹人烦的东西这边来

回复
 
LinkBack 主题工具 显示模式
  #1 (permalink)  
旧 2005-06-08
up2009 的头像
普通会员
 
注册日期: 2005-05-11
帖子: 37
up2009 正向着好的方向发展
默认 初学者问题之六

#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main()
{
double average;
average=2/3;
cout<<average;
}
程序结果:0 ??????????

为什么不是0.666667。

而:
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main()
{
//ex=x/1!+x*x/2!+x*x*x/3!......
int u,v,x,y=1;
double t=0,e=1;
cout<<"x=";
cin>>x;
v=x;
while (x>=1)
{
u=x,y=1,e=1;
while(u>=1)
{
e*=u ;
y*=v ;
u--;
//cout<<e<<endl<<y<<endl;
}
t+=y/e ;
cout<<t<<endl;
x--;
}
cout<<t;
}

程序结果有小数的;
这是为何??????

在DEVC++下测试。
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #2 (permalink)  
旧 2005-06-08
cat cat 当前离线
高级会员
 
注册日期: 2003-11-06
帖子: 1,563
文章: 6
cat 正向着好的方向发展
默认

int / int 还是int, 所以2/3 = 0
2.0/3.0 = 0.66666666666667
2 / 3.0 = 0.66666666666667
2 / (double)3 = 0.666666666667
2.0/3 = 0.6666666666667
有关这个规则,去网上搜一下或者看那些经典教科书。
当字面量的时候还好,如果是变量就更要小心了。

大体规则是有一个double参与这个局部的计算,那么整个计算就基于double进行。(具体是表达式局部,还是用于真个表达式,忘记了
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #3 (permalink)  
旧 2005-06-08
wqqafnd 的头像
高级会员
 
注册日期: 2004-10-08
帖子: 196
文章: 1
wqqafnd 正向着好的方向发展
发送 MSN 消息给 wqqafnd
默认

楼主其实不需要拘泥于这些细节,书看得多了,自然就明白这些东西了。
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #4 (permalink)  
旧 2005-06-08
bankrock 的头像
高级会员
 
注册日期: 2003-12-11
帖子: 847
文章: 7
bankrock 正向着好的方向发展
默认

这个不能说拘泥不拘泥吧,这是个比较隐蔽的问题,直接在书上找不到,估计不少人都吃过亏吧。
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
  #5 (permalink)  
旧 2005-06-10
up2009 的头像
普通会员
 
注册日期: 2005-05-11
帖子: 37
up2009 正向着好的方向发展
默认

非常感谢!
谢谢大家了
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
回复时引用此帖
回复

书签
主题工具
显示模式

发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛启用 表情符号
论坛启用 [IMG] 代码
论坛禁用 HTML 代码
Trackbacks are 启用
Pingbacks are 启用
Refbacks are 启用



所有时间均为格林尼治时间 +9。现在的时间是 09:11 AM


Powered by vBulletin® 版本 3.7.0
版权所有 ©2000 - 2009,Jelsoft Enterprises Ltd.
(C) Copy Right All Right Reserved 2001 - 2007

Search Engine Friendly URLs by vBSEO 3.1.0