I wrote a program to calculate the sum of a harmonic series (1 + 1/2 + 1/3 .. + 1/n), but I’m having trouble compiling it. I went over the code a bunch of times but I don’t see any syntax errors [2 are showing up when I try to compile]. Is my logic wrong, or is it syntactical?
#include <stdio.h>
int main( void ) {
int v,p,i;
double x=0;
printf("Enter a value to calculate the value of this harmonic series: \n");
scanf("%d",&v);
if (v<=0) {
printf("Please enter a POSITIVE number: \n");
scanf("%d",&p);
while (i=1; i<=v; i++) {
x=x+(1/i); }
printf("The value for the series is %lf", x);
}
else {
while (i=1; i<=v; i++) {
x=x+(1/i);
}
printf("The value for the series is %lf", x);
}
return 0;
}
Thanks for any help
All those
whileshould befor, and that1/ishould be either1./ior1/(double)i, because otherwise an integer division is performed. Also, you should restructure your program flow to avoid that code duplication.But, there’s a subtle but more important mistake: due to how floating point arithmetic works, you should start to sum from smaller numbers to big ones, otherwise you may reach the point were each new addend is smaller than the current precision of that
double, and the addition will have no effect1. So, yourforshould be reversed:Also: you should check the return value of the
scanfto be 1, to make sure that the user actually inserted some valid numeric input. And, theprintfspecifier fordoubles is just%f, without thel.Taking all this in account, you could rewrite the program as this: