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

Clarify the difference in representation of numbers

P: 48
Expand|Select|Wrap|Line Numbers
  1. void main()
  2. {
  3.   float me = 0.7;
  4. if(me<0.7)
  5. printf("C");
  6. else
  7. printf("C++");
  8. }
For the above code my compiler prints as C

However for the code
Expand|Select|Wrap|Line Numbers
  1. void main()
  2. {
  3.   float me = 1.7;
  4. if(me<1.7)
  5. printf("C");
  6. else
  7. printf("C++");
  8.  
my compile prints as C++.

Hence kindly clarify why is the above difference?
Aug 29 '10 #1
Share this Question
Share on Google+
4 Replies


100+
P: 542
and where do you change the values of me? ......to trigger the print op?
Aug 30 '10 #2

P: 48
I am not changing the value of me anywhere.
In the first program the if statement compares whether me(i.e.0.7) is lesser than 0.7 and the above decision turns true.

In my next code the value of me is 1.7 and when i compared me(i.e. 1.7) with 1.7 the decision shows that me is greater than 1.7.

At first i though me is float and if we speify a number with decimal point explicitly compiler will treat that as double and hence in the first case me<0.7. But this doesn't works for my second code. Hence kindly clarify
Aug 30 '10 #3

Expert 100+
P: 2,398
Take a look at what every computer scientist should know about floating point.

When assigning a value to me, the value is effectively cast to a float. When comparing me to a value, me is effectively cast to a double. When does changing from one floating point type to another change the value? It depends on implementation-dependent features of the underlying representation.
Aug 30 '10 #4

P: 4
In this kind of comaprisions, 99% of the time the else part of the if condition gets executed.

In this example, when you try to compare 0.7 with 0.7, what actually happens internally is, one of the 0.7 is interpreted as 0.6999999999.

Floating point representation is machine dependent.

Even though there is not much of a difference between 0.7 and 0.6999999999, the if condition fails.

You execute the same code on another machine, probably you will get another result.

So, never use floating numbers for comparision.
Sep 3 '10 #5

Post your reply

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