+ 1

trying to get harmonic progression sum in c...........help me....

here's my code.... #include <stdio.h> #include <stdlib.h> int main() { int x, n; x = 1; double y; y = 0.0; printf("Enter a number:\n"); scanf("%d", &n); while(x<=n) { y = y + 1/x; x = x + 1; } printf("%.1f", y); return 0; } tell me...what did i do wrong

19th Nov 2020, 1:45 PM
yodha gopal
yodha gopal - avatar
2 Antworten
+ 6
`x` is an int, and so is `1`, so `1/x` does integer division! The result will be rounded down to the next int, which is always 0 here. Replace `1/x` with `1.0/x` or `1f/x` and it should work.
19th Nov 2020, 3:04 PM
Schindlabua
Schindlabua - avatar
+ 1
Thank you Schindlabua....it worked!!!!
20th Nov 2020, 12:57 AM
yodha gopal
yodha gopal - avatar