Why does
result = static_cast<double>(1 / (i+1))
return int
in C++ and why does
result = 1 / (i+static_cast<double>(1))
return double
? Specifically why is casting after the +
-operation sufficient to produce a double
. Why is it not required before the +
or in the numerator as well? Is static_cast
the preferred way of casting?
Code:
double harmonic(int n) {
double result = 0;
for (int i = 0; i < n; i++) {
result += 1 / static_cast<double>(i+1);
}
return result;
}