(float answer = 1/3) = 0?!

Why does this equal zero?

Page 1 of 1

3 Replies - 4167 Views - Last Post: 27 August 2009 - 03:15 PM Rate Topic: -----

#1 IngeniousHax   User is offline

  • |>|20-514<|{3|2

Reputation: 84
  • View blog
  • Posts: 1,385
  • Joined: 28-March 09

(float answer = 1/3) = 0?!

Posted 27 August 2009 - 03:09 PM

#include <stdio.h>
#include <stdlib.h>

int main(){
	 float answer = (1 / 3);

	printf("Why does this equal zero ---> %f\n", answer);
	return(0);
}



I can't figure out why is equals zero... should equal .3333333

This post has been edited by IngeniousHax: 27 August 2009 - 03:10 PM

Is This A Good Question/Topic? 0
  • +

Replies To: (float answer = 1/3) = 0?!

#2 Guest_Neumann*


Reputation:

Re: (float answer = 1/3) = 0?!

Posted 27 August 2009 - 03:11 PM

Because you're dividing integers. Integers don't have decimal places, they truncate everything.

float answer = (1.f / 3);



Now you're dividing a float by integer, in which case the result is also a float and thus retains the decimal places.

This post has been edited by Neumann: 27 August 2009 - 03:14 PM

Was This Post Helpful? 1

#3 IngeniousHax   User is offline

  • |>|20-514<|{3|2

Reputation: 84
  • View blog
  • Posts: 1,385
  • Joined: 28-March 09

Re: (float answer = 1/3) = 0?!

Posted 27 August 2009 - 03:12 PM

Doh, they need to be 1.0 and 3.0 huh?
Was This Post Helpful? 0
  • +
  • -

#4 Guest_Neumann*


Reputation:

Re: (float answer = 1/3) = 0?!

Posted 27 August 2009 - 03:15 PM

Well, in that case you will be dividing doubles. Better stick an f at the end to make them floats. Also note that only one of them needs to be float.
Was This Post Helpful? 0

Page 1 of 1