# about variable declaration

wei liu

Ranch Hand

Posts: 56

posted 14 years ago

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......

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......

Kaspar Dahlqvist

Ranch Hand

Posts: 128

posted 14 years ago

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

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