English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I am taking an intro to prorgamming class and I have come across a question to which I have no clue of the answer. I am usually very objected to simply putting a homework question out to receive an answer, but I have exhausted all other methods of understanding why this is happening.

We're using DrJava which has a small pane where you can just input code and get an instant result. They have me enter the following:
int x = 1 / 3; System.out.println(x);
and
double d1 = 1 / 3; System.out.println(d1);

Both of which give me 0 and 0.0 respectivly as the result. I expected it for the first one, but I expected when I changed the type to double or float it would give me 0.33, not 0.0. I am totally lost as to why this is happening. Any help would be greatly appreciated. Thanks for any bit of help.

2006-09-10 12:21:55 · 3 answers · asked by loudgrrl4_ever 2 in Computers & Internet Programming & Design

3 answers

Try doing

double d1 = 1.0 /3.0; System.out.println(d1);

I think (I'm not sure) that if you use integers in division, you will always get an integer result. It changes the type to double after doing the math and coming up with an integer result.

So what happens is 1/3 = 0, double 0 = 0.0, if that makes any sense. So to get a decimal result, you have to use decimals in the division.

2006-09-10 12:29:07 · answer #1 · answered by Bryan A 5 · 0 0

I agree with the previous posters
double d1=1/3 is bound to give you zero.
That is because the casting to double happens after the division and the division is between integers which have already resulted in zero before getting assigned to a double

d1=1.0/3
d1=1/3.0
d1=1.0/3.0
etc would give you the answer you are looking for

2006-09-10 17:53:05 · answer #2 · answered by Neil 5 · 0 0

Because of that :double d1=1/3; the default means: int/int; so it will be 0.0;
that you give 1.0/3/0 will be 0.33333333,if your are use jdk 5.0 ,had a see of System.out.printf();

2006-09-10 17:19:12 · answer #3 · answered by Jimmy 1 · 0 0

fedest.com, questions and answers