// Chapter 2 , Problem 6 (wrk2c.cc) USING 'if' to handle errors /* -------------Problem------------ Program needs to read numerator and denominator of 2 fractions, then display the product of both fractions as a percent and a fraction. A valid fraction can not have a zero or negative denominator. Zero denominators are handled in a unfriendly way... rejection. -------------Analysis----------- DATA REQUIREMENTS Constants 100 = percent decimal adjustment Inputs 2 Numerators (int) 2 Denominators (int) Outputs percent (double) - Product of 2 fractions represented as a persent. num_product (int) - Product of 2 numerators den_product (int) - Product of 2 denominators FORMULAE Nothing more than multiplication of two fractions and integer division. --------------Design------------- INITIAL ALGORITHM 1. Get the first fraction from user 2. Get the second fraction from user 3. Calculate the fractional representation of the product of the two fractions. 4. Display the result as a fraction. 5. Calculate the percentage of the product of the two fractions. 6. Display the percentage result. REFINEMENTS ------------Implementation--------- KNOWN PROBLEMS Entering a floating point number for any numerator or denominator is undefined, and makes the program do strange things. */ /* Some preset literals */ const int error = 1; const int ok = 0; #include int main( void ) { const double percent_adjust = 100.0;//will force conversion to double... int num1, den1 , num2 , den2 , num_product, den_product; double percent; /* Get the first fraction from the user */ cout << "Please enter the numerator of fraction one: "; cin >> num1; cout << "Please enter the denominator of fraction one (non-zero): "; cin >> den1; //Verify that the denominator of the first fraction was non-zero if (den1 == 0) { //Report error and terminate program cerr<< "Fractions must have a denominator that is not zero!\n"; return (error); } // fix up negative, nonzero denominator if (den1 < 0) { num1= -num1; den1= -den1; } cout << "Please enter the numerator of fraction two: "; cin >> num2; cout << "Please enter the denominator of fraction two (non-zero): "; cin >> den2; //Verify that the denominator of the second fraction was non-zero if (den2 == 0) { //Report error and terminate program cerr<< "Fractions must have a denominator that is not zero!\n"; return (error); } // fix up negative, nonzero denominator if (den2 < 0) { num2= -num2; den2= -den2; } //We now have two valid fractions num_product = num1 * num2; den_product = den1 * den2; //Display results cout << "The resulting fraction is: " << num_product << "/" << den_product << endl; cout << "Which is " << (percent_adjust*num_product/den_product) << "%" << endl; return ok; }