#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;
}
|