programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

# about variable declaration

Ranch Hand
Posts: 56
• Number of slices to send:
Optional 'thank-you' note:
Which of the following are legal statements?
1) float f=1/3;
2) int i=1/3;
3) float f=1.01;
4) double d=999d;
Answer to Question 1)
Objective 4.5)
1) float f=1/3;
2) int i=1/3;
4) double d=999d;
The fact that option 3 does not compile may be a surprise. The problem is because the default type for a number with a decimal component is a double and not a float. The additional trailing d in the option with 999 doesn't help, but it doesn't harm.
----------
i m confused about the 2nd ans,why is it correct? i suppose int should not be initialized like int i=1/3, since the result would be int i =0.333333......

Ranch Hand
Posts: 128
• Number of slices to send:
Optional 'thank-you' note:
Hello!
Have you tried executing any of these little snipplets? Isn't it strange that the result of
float f = 1/3;
is 0.0? The reason for this is also the reason why
int i = 1/3;
executes.
Actually, both 1 and 3 are integers. Right? And if you divide one int with another, the answer, too, will come in the shape of an int. In ordinary math, 1/3 yields 0.33333. But as an int cannot store the decimal part, the result will be 0. This result can then be stored in an int, in which case the int's value will be 0. The result can also be stored in a float, in which case the float's value will be 0.0...
I recommend reading RHE, chapter 2, "The Arithmetic Operators".
Hope this helps!
//Kaspar

 Don't get me started about those stupid light bulbs.
reply
Similar Threads