*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why float f=1/3 is 0? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why float f=1/3 is 0?" Watch "why float f=1/3 is 0?" New topic
Author

why float f=1/3 is 0?

michael wang
Ranch Hand

Joined: Feb 06, 2002
Posts: 35
it compiles and print 0.0
why?
thanks


--<br />a java beginner from China
Nazmul Huda Sarkar
Ranch Hand

Joined: Feb 01, 2002
Posts: 317
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 ?


Nazmul<br />SCJP,SCWCD,IBM OOAD with UML
michael wang
Ranch Hand

Joined: Feb 06, 2002
Posts: 35
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

Joined: Sep 22, 2001
Posts: 2578

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

Joined: Jul 03, 2001
Posts: 2120
Michael
float e = (float)1.0/3
compiles ok


SCJP2. Please Indent your code using UBB Code
michael wang
Ranch Hand

Joined: Feb 06, 2002
Posts: 35
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

Joined: Feb 01, 2002
Posts: 317
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

Joined: Feb 08, 2002
Posts: 14
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
 
Don't get me started about those stupid light bulbs.
 
subject: why float f=1/3 is 0?
 
Similar Threads
:mad: Bali Bombing!!!
Do you give money to beggars?
java and c++ comparison
How About Avatars?
Why does Groovy have this name?