The output always equals to 1 and the mathimatical equation can't be completed
for (int i = 1; i <= x; i += 2) {
sum += 1 / i;
}
I expected the output of sum equals 4/3 when x equals 3 ,but the actual output is 1.
The output always equals to 1 and the mathimatical equation can't be completed
for (int i = 1; i <= x; i += 2) {
sum += 1 / i;
}
I expected the output of sum equals 4/3 when x equals 3 ,but the actual output is 1.
In languages like C, C++, and Java, dividing two integers rounds towards zero. So if I have:
int x = 3 / 5;
Then x == 0
because it rounded towards 0. Fixing this is pretty simple - just use a double
instead of an int
:
double sum = 0.0;
for(int i = 0; i <= x; i += 2) {
sum += 1.0 / i; // 1.0 is a double, so division works as intended
}