

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


/* HarmonicError.c / / Computes the harmonic series until a difference is reached */ #include <stdio.h>
int main() { /* declarations of input and output variables / double diffgoal; / difference between sums of terms requested / double sumterms; / result of summing the squares */
/* declarations of additional variables / double inverseterm; / compute each term, the inverse / double lastsum; / the previous sum of terms in the series / double diffachieved; / difference between sums of terms so far / int index; / index variable to count loop repetitions */
/* ask the user how much precision is required to compute the series */ printf("How much difference between sums of terms should be achieved? \n"); printf("Please enter a number less than 1> "); scanf("%lf", &diffgoal);
/* initialize the sum to zero */ sumterms = 0;
/* initialize the difference so far to 1 (the largest difference) and the last sum */ diffachieved = 1.0; lastsum = 0;
/* initialize the index variable */ index = 1;
/* compute the harmonic series of terms until the difference between the sums of terms meets the goal / while (diffachieved >= diffgoal) { / compute the inverse of the index and add to the sum */ inverseterm = 1.0 / index; sumterms = sumterms + inverseterm;
/* compute the difference between this sum and the previous one, reset the last sum variable */ diffachieved = sumterms - lastsum; lastsum = sumterms;
/* increment the index variable */
index++; } // end of for loop
/* print the result */ index = index - 1; // to get the number of the last term printf("The harmonic series computed from %i terms is %lf.\n", index, sumterms);
return(0); }