| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1019 人关注过本帖
标题:【共享】把任意浮点数转化成满足指定精度最简分数
只看楼主 加入收藏
shan183
Rank: 1
等 级:新手上路
帖 子:60
专家分:0
注 册:2005-5-30
收藏
 问题点数:0 回复次数:1 
【共享】把任意浮点数转化成满足指定精度最简分数
#include <cmath> #include <iostream> using namespace std; int main() //浮点数转化成最简分数 { int n=1,m=1,nn,mm; //分子分母 int sign=1; //存储所输入数字的符号 int intPart=0; int common; //存储分子分母的公约数 double x,d; //x存储所输入数字的小数部分 d=0.001; //指定精确度 cout<<"Input a number you want to transform,"; cout<<"or input an integer to stop the program:"<<endl; cin>>x; sign=x/fabs(x); if(fabs(x)>=1) intPart=static_cast<int>(fabs(x)); x=fabs(x)-intPart; while(x!=0) { while (fabs(1.0*n/m-x)>=d) { if(x<1.0*n/m) m++; if(x>1.0*n/m) n++; } nn=n; mm=m; common=m%n; while(common) { m=n; n=common; common=m%n; } common=n; m=mm/common; n=nn/common+intPart*m; cout<<"Result:"<<sign*n<<"/"<<m<<endl; cout<<"Input a number you want to transform,"; cout<<"or input an integer to stop the program:"<<endl; cin>>x; intPart=0; n=1; m=1; sign=x/fabs(x); if(fabs(x)>=1) intPart=static_cast<int>(fabs(x)); x=fabs(x)-intPart; } return 0; } 运行结果: Input a number you want to transform,or input an integer to stop the program: -5.625 Result:-45/8 Input a number you want to transform,or input an integer to stop the program: 7.6333 Result:229/30 Input a number you want to transform,or input an integer to stop the program: 0.88888 Result:8/9 Input a number you want to transform,or input an integer to stop the program: -0.777999 Result:-74/95 Input a number you want to transform,or input an integer to stop the program: 20 Press any key to continue
挑战自己,超越自己,成就自己!

[此贴子已经被作者于2005-6-18 17:03:01编辑过]

搜索更多相关主题的帖子: 精度 点数 最简分数 
2005-06-16 09:45
风の影子
Rank: 2
等 级:新手上路
威 望:3
帖 子:664
专家分:0
注 册:2005-5-19
收藏
得分:0 
帮顶个!!!
2005-06-17 13:04
快速回复:【共享】把任意浮点数转化成满足指定精度最简分数
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.010704 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved