435,640 Members | 2,355 Online + 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 #include  using namespace std;  int main () {    int numberOfStems=100;    float lowMark=1/4;    cout << "Low Mark= " << lowMark <
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 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 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 double lowMark=1.0/4.0; :p Sep 18 '10 #4

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