标签:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include <stdlib.h> #include <iostream.h> #include <math.h> int main() { int iDecimal; int iNumerator, iDenominator, iNegative; double dFraction, dDecimal, dAccuracy, dInteger; cout << "请输入你要转换的数:" ; cin >> dDecimal; iDecimal = ( int )dDecimal; //取整数部分,以在下一步判断输入的是否为整数 if (iDecimal == dDecimal) //判断输入是否为整数,若是则直接输出 { cout << dDecimal << endl; return 0; } if ( abs (iDecimal) >= 1) //如果输入大于等于1,则分解为整数部分和小数部分 { dInteger = iDecimal; dDecimal = dDecimal - iDecimal; } dAccuracy = 0.0001; //设置精度 iNumerator = 0; //初始分子 iDenominator = 1; //初始分母 iNegative = 1; //负数标志 if (iDecimal <0) iNegative = -1; dFraction = 0; while ( fabs (dFraction - dDecimal) > dAccuracy) //判断精度是否达到要求 { if ( fabs (dFraction) > fabs (dDecimal)) iDenominator = iDenominator + 1; //增加分母 else iNumerator = iNumerator + iNegative; //增加分子 dFraction = ( double )iNumerator / ( double )iDenominator; //计算新的分数 } if ( abs (iDecimal) >= 1) cout << dInteger << ‘+‘ << ‘(‘ << iNumerator << ‘/‘ << iDenominator << ‘)‘ << endl; else cout << iNumerator << ‘/‘ <<iDenominator << endl; return 0; } |
标签:
原文地址:http://www.cnblogs.com/zhxshseu/p/5285647.html