// Compile with "g++ rattest.cpp" #include #include using namespace std; int main () { double decPart; // assign the decimal part of the given value int num = 0; int den = 1; int exp, tempDen, tempNum; double delta, delta2; double ftemp; decPart = 2.0; // force into while loop while ((decPart >= 1.0) || (decPart < 0.0)) { cout << "Enter a value in the range of [0.0 .. 1.0): "; cin >> decPart; } if (decPart != 0.0) { // set for 0/1 delta = decPart; // check if fraction should be 1/1 if (fabs(1.0 - decPart) < delta) { delta = fabs (1.0 - decPart); num = 1; den = 1; } // loop for denominator value for (exp = 1; exp <= 7; exp++) { tempDen = int (pow (2, exp)); // cout << "den: " << tempDen << ", "; for (tempNum = 1; tempNum < tempDen; tempNum += 2) { delta2 = fabs(decPart - (double(tempNum)/double(tempDen))); // cout << delta2 << ' '; if (delta2 < delta) { delta = delta2; num = tempNum; den = tempDen; // cout << '*' << tempNum << ", " << delta << "* "; } } // cout << endl; } } cout << "The Fraction for " << decPart << " is: " << num << '/' << den << endl; cout << "As a float it is: " << double(num)/double(den) << endl; cout << "Amount of Error: " << fabs(decPart - (double(num)/double(den))) << endl; }