I have to write program that gets a number n
from the user, and then calculates the sum: s = 1/1 + 1/2 + ... + 1/n.
I wrote this code:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner unos = new Scanner(System.in);
System.out.println("n=?");
int n = unos.nextInt();
double s = 0.0;
for (int i = 1; i <= n; i++) {
s = s + (1.0 / i);
}
System.out.println("s=" + s);
}
}
How does Java decide to convert the int value i
into double in this statement:
s = s + (1.0 / i);
The rules that govern what type gets converted/promoted to what other type are defined in the Java Language Spec Chapter 5 - Conversions and Promotions.
Specifically for most arithmetic operations, look at the Binary Numeric Promotion section.
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value of a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:
- If either operand is of type double, the other is converted to double.
- Otherwise, if either operand is of type float, the other is converted to float.
In your case, 1.0 is a double, so i
is converted to a double (widening conversion). Since s
already is a double, no further conversion is necessary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With