Why does C++ give the wrong answer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HughLafferty
    New Member
    • Sep 2010
    • 2

    Why does C++ give the wrong answer

    Code:
    #include <iostream>
    using namespace std; 
    int main ()
    {
       int numberOfStems=100;
       float lowMark=1/4;
       cout << "Low Mark= " << lowMark <<endl; //This outputs 0
       cout << "Pass Mark=" << 40*numberOfStems/100 << endl; //This outputs 40
       return 0;
    }
    I am using VS8 and compile and run with Ctrl+F5
    Last edited by Banfa; Sep 18 '10, 10:20 AM. Reason: Corrected code tags
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    It doesn't in both cases it outputs the correct number or rather the number you asked it to calculate.

    Simple case first

    40*numberOfStem s/100 where numberOfStems = 100

    40*100/100 = 40

    The case that is probably confusing you

    float lowMark=1/4;

    You have chosen to store the result in a float (best practice is to use double rather than float unless you have an communicable reason why floats should be used) because you are expecting a fraction, that is good.

    However you have written 1/4 both 1 and 4 are integers so it does integer arithmetic under integer arithmetic 1/4 = 0. Having calculated 0 it converts it to a float for storage.

    You need to force it to do floating point arithmetic, the easiest way to do that is to use floating point constants rather than integer constants like this

    float lowMark=1.0/4.0;

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Code:
      float lowMark=1.0/4.0;
      Actualy, 1.0 and 4.0 are double. This will prompt a warning frim the compiler about possible loss of accuracy when string in the smaller float.

      You should code:

      Code:
      float lowMark=1.0f/4.0f;

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        If we are going to get picky then since we all agree that you should use double rather than float you should code
        Code:
        double lowMark=1.0/4.0;
        :p

        Comment

        • HughLafferty
          New Member
          • Sep 2010
          • 2

          #5
          Thank you to weaknessforcats for giving me a reply.

          Comment

          Working...