找回密码
 注册
搜索
热搜: 回贴
  • 前程无忧官网首页 有什么好的平台可以
  • 最新的销售平台 互联网营销的平台有哪
  • 制作网页的基本流程 网页制作和网页设
  • 【帝国CMS】输出带序号的列表(数字排
  • 网站建设公司 三一,中联,极东泵车的
  • 织梦 建站 织梦网站模版后台怎么更改
  • 云服务官网 哪些网站有免费的简历模板
  • 如何建网站要什么条件 建网站要用什么
  • 吉林市移动公司电话 吉林省退休人员网
  • 设计类毕业论文 网站设计与实现毕业论
查看: 1086|回复: 1

【共享】把任意浮点数转化成满足指定精度最简分数

[复制链接]
发表于 2009-10-31 01:45:50 | 显示全部楼层 |阅读模式 IP:江苏扬州
#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

挑战自己,超越自己,成就自己!
发表于 2009-10-31 01:45:51 | 显示全部楼层 IP:江苏扬州
帮顶个!!!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )

GMT+8, 2024-9-29 15:25 , Processed in 0.249930 second(s), 12 queries , Gzip On, MemCache On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表