|
#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
挑战自己,超越自己,成就自己! |
|