Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
September 24, 2017, 07:00:58 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
 
   Home   Help Search Login Register Chat  
Pages: [1]   Go Down
  Print  
Author Topic: Prog2.4 -- adding floats give wrong answer?  (Read 8543 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:  

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 ゥ 2009 classroomM.com. All rights reserved.