I keep getting 1 1 1 1 1 outputted when I am trying to show the float values of 1, 1/2, 1/3..... 1/n. How do I fix this?
Asked
Active
Viewed 54 times
-2
-
1Please edit your question and post the code as text. There's no easy way to try code in an image ourselves, nor can we we copy it into our answers, and it won't show up in future Google searches. See: [Why not upload images of code on SO when asking a question?](https://meta.stackoverflow.com/q/285551/68587) – John Kugelman Sep 15 '20 at 03:02
-
Sounds like you're using `int` when you should be using `double`. – tadman Sep 15 '20 at 03:03
-
1Does this answer your question? [Division in C++ not working as expected](https://stackoverflow.com/questions/6101084/division-in-c-not-working-as-expected) or [Integer division always zero](https://stackoverflow.com/questions/9455271/integer-division-always-zero) – John Kugelman Sep 15 '20 at 03:04
1 Answers
0
Although sum
is of float type, i
is not. By doing 1/i
you are doing int/int
division which evidently rounds down.
What's happening is this: 1/1 + 1/2 + ... + 1/n
= 1 + 0 + ... + 0
= 1.
You can resolve this by casting or changing the type of i
.
A simple solution could be:
sum = sum + ((float)1 / i);
Or even:
sum = sum + (1.0/i);

jiejasonliu
- 1
- 1