Amazon.com Widgets Prog2.4 -- adding floats give wrong answer?
Welcome, Guest. Please login or register.
Did you miss your activation email?
July 30, 2014, 06:07:29 AM
Home Help Search chat Login Register 
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+ Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+ Programming in Objective-C, 4th edition
| |-+ Chapter 2
| | |-+ Prog2.4 -- adding floats give wrong answer?
Pages: [1] Go Down
Print
Author Topic: Prog2.4 -- adding floats give wrong answer? (Read 2528 times)
rue
Jr. Member
**
Posts: 53






on: April 21, 2012, 07:19:50 PM

Based on Progr 2.4, I tried using float numbers.


Code: (Objective-C)
float sum;
       
        sum = 50.5 + 25.12;
        NSLog(@"The sum of 50.5 and 25.12 is %f",sum);

But Xcode says the answer is:
The sum of 50.5 and 25.12 is 75.620003

What gives?
Where did the 0.000003 extra value came from?
Logged
rue
Jr. Member
**
Posts: 53






Reply #1 on: April 21, 2012, 07:24:50 PM

Okay, found the answer to my question.

This one works. i.e. using double instead of float.
The question is why?

Code: (Objective-C)
   double sum;
       
        sum = 50.5 + 25.12;
        NSLog(@"The sum of 50.5 and 25.12 is %f",sum);


 The sum of 50.5 and 25.12 is 75.620000
Logged
MacLovin
Newbie
*
Posts: 1






Reply #2 on: November 12, 2013, 03:10:14 PM

I start learning Objective-C recently, and also curious about the reason.
Logged
aka
Newbie
*
Posts: 1






Reply #3 on: March 28, 2014, 05:05:24 PM

As float is represented in binary code(0, 1), there is no exact 0.1 possible. In fact computers cant calculate with numbers exactly. They can only represent a number very close to the number you entered.

More informations:
http://floating-point-gui.de/
Logged
Pages: [1] Go Up
Print
Jump to:



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.