Friday, July 31, 2009

C++ Program question How can I getthis working?

menu();





cin %26gt;%26gt; functionType;





while(functionType != 9)


{


cout %26lt;%26lt; "For fraction 1" %26lt;%26lt; endl;


cout %26lt;%26lt; "Enter the numerator: ";


cin %26gt;%26gt; numOne;


cout %26lt;%26lt; endl;


cout %26lt;%26lt; "For fraction 1" %26lt;%26lt; endl;


cout %26lt;%26lt; "Enter the denominator: ";


cin %26gt;%26gt; denOne;


cout %26lt;%26lt; endl;





cout %26lt;%26lt; "For fraction 2" %26lt;%26lt; endl;


cout %26lt;%26lt; "Enter the numerator: ";


cin %26gt;%26gt; numTwo;


cout %26lt;%26lt; endl;


cout %26lt;%26lt; "For fraction 2" %26lt;%26lt; endl;


cout %26lt;%26lt; "Enter the denominator: ";


cin %26gt;%26gt; denTwo;


cout %26lt;%26lt; endl;





if (functionType != 9)


switch(functionType)


{


case '+':





cout %26lt;%26lt; addFractions %26lt;%26lt; endl;


break;


}


case '-':


{





cout %26lt;%26lt; subtractFractions %26lt;%26lt; endl;


break;


}


case '*':


{





cout %26lt;%26lt; multiplyFractions %26lt;%26lt; endl;


break;


}


case '/':


{





cout %26lt;%26lt; divideFractions %26lt;%26lt; endl;


break;


}

C++ Program question How can I getthis working?
If this compiles at all, you'll see stange numbers. That is because:


cout %26lt;%26lt; addFractions %26lt;%26lt; endl;


would print the function pointer of addFractions , not the return of addFractions ();





Try:


cout %26lt;%26lt; addFractions() %26lt;%26lt; endl;








I think a better flow would be


Write a double parseFractionString(String fraction) method.





1. Print%26gt;Enter the first fraction in the form a/b. Example 3/4.


User enters %26gt;4/5





2. Save double fract1 = parseFractionString(user input) and catch any error, give user a chance to correct.





3. Enter the sign (+ - * /)


User enters %26gt;*





4. Save char operator as first char of user input


and catch any error, give user a chance to correct.





5. Save double fract2 = parseFractionString(user input) and catch any error, give user a chance to correct.





The switch statement on operator.





then each case is just





switch (operator) {


case '*':


result = parseFractionString(fract1) * parseFractionString(fract2);


break;





case '+':


result = parseFractionString(fract1) + parseFractionString(fract2);


break;


No comments:

Post a Comment