By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,640 Members | 2,355 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,640 IT Pros & Developers. It's quick & easy.

Why does C++ give the wrong answer

P: 2
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. using namespace std; 
  3. int main ()
  4. {
  5.    int numberOfStems=100;
  6.    float lowMark=1/4;
  7.    cout << "Low Mark= " << lowMark <<endl; //This outputs 0
  8.    cout << "Pass Mark=" << 40*numberOfStems/100 << endl; //This outputs 40
  9.    return 0;
  10. }
I am using VS8 and compile and run with Ctrl+F5
Sep 18 '10 #1
Share this Question
Share on Google+
4 Replies

Expert Mod 5K+
P: 8,916
It doesn't in both cases it outputs the correct number or rather the number you asked it to calculate.

Simple case first

40*numberOfStems/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;
Sep 18 '10 #2

Expert Mod 5K+
P: 9,197
Expand|Select|Wrap|Line Numbers
  1. 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:

Expand|Select|Wrap|Line Numbers
  1. float lowMark=1.0f/4.0f; 
Sep 18 '10 #3

Expert Mod 5K+
P: 8,916
If we are going to get picky then since we all agree that you should use double rather than float you should code
Expand|Select|Wrap|Line Numbers
  1. double lowMark=1.0/4.0;
Sep 18 '10 #4

P: 2
Thank you to weaknessforcats for giving me a reply.
Sep 19 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.