Java int vs. Double

2019-08-29 05:46发布

问题:

public double calc(int v1) {
return v1 / 2 + 1.5;
}


public double cald (double v) {
return v / 2 + 1.5;
}

Do the functions return the same result?

I would argue that they don't return the same result, as the second function would include the decimal point, where as the second function would round the number up.

Is that correct?

回答1:

when you divide a by b i.e a/b

if both a & b are int then result will be int
else any or both a & b are double then result will be double

Edit:

Also see my answer to this Question Simple Divide Problem



回答2:

They don't: see sample on IDEONE, clone it and play with it.

System.out.println(calc(1));// gives 1.5
System.out.println(cald(1.0));// gives 2.0


回答3:

int v1 = 1;
return v1 / 2 + 1.5; // = 1.5

it is an integer divided by an integer more double. Or in your case 1 / 2, that it is 0.5, but it is a division amoung ints, so will be 0, more 1.5, return 1.5.

double v = 1.0;
return v / 2 + 1.5; // = 2.0

This case, the division is between an double and an int, returning an double of value 0.5, summing with 1.5 will return 2.0.



回答4:

They don't return the same. / on default is integer division if the numbers are integers, i.e., the result of a/2 is an integer without the reminder if a is an integer. while if a is a double, then the result of this division is a double.

5/2 = 2
5.0/2 = 2.5