Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why float f=1/3 is 0?

 
michael wang
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it compiles and print 0.0
why?
thanks
 
Nazmul Huda Sarkar
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
here 1 and 3 both r integer..right? so an integer division 1/3 = 0 then 0 is promoted to
float...so it is 0.0
float f = 1/3
float f = (float) (1/3)
float f = (float) (0)
so f=0.0

but if it is 1.0/3 or 1/3.0 then the result would be different...'coz first both will be promoted to float and it would then be a floating point division....
am I right ?
 
michael wang
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
float f=(float)(1.0/3.0);
System.out.println(f);//print 0.33333334
float d = 1/3;
System.out.println(d);//print 0.0
//float e = 1.0/3;//compile time error
//float e = 1/3.0;//compile time error
//float e = (float)1.0/3;//compile time error
}
}
 
Manish Hatwalne
Ranch Hand
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by michael wang:
float f=(float)(1.0/3.0);
System.out.println(f);//print 0.33333334
float d = 1/3;
System.out.println(d);//print 0.0
//float e = 1.0/3;//compile time error
//float e = 1/3.0;//compile time error
//float e = (float)1.0/3;//compile time error
}
}

1.0 as or 3.0 is a double value. Use 1.0f and 3.0f etc.
HTH,
- Manish
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael
float e = (float)1.0/3
compiles ok
 
michael wang
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jose Botella:
Michael
float e = (float)1.0/3
compiles ok

sorry for that
i want to say
float e=(float)1.0/3.0
 
Nazmul Huda Sarkar
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ofcourse proper syntax must be taken care of but if u understand why float f=1/3 result 0.0 and float f=(float)1/3 result 0.33333 , then its ok.
 
Stefan Koeltze
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!
3.0 by default is a double!!!
(float)1.0/3;
is the same as:
(float)1.0/(int)3; and a int will be expanded to a float ... so there is no problem.
(float)1.0/3.0;
is the same as:
(float)1.0/(double)3.0; so we hav incompatible types ... so without casting we have a compile error.
(float)(1.0/3.0);
is by default the same as:
(float)((double)1.0/(double)3.0);
...so ... no problem
Ok!?
Ciao Stefano
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic