Need help with series for loop

Hello everyone,
I am a newbie to C++ and programing. I am in need of help in a lab:
Write a program to calculate and print the result of the following series operations for the given values of x:
The series should be calculated using floats and doubles for the values for x that are specified.

f(x) =∑(n=1)^x[1/n]

f(100,000,000) =∑ (n=1)^100,000,000 [1/n] = 1/1 + 1/2 + 1/3 + ... + 1/99999999 + 1/100,000,000

This is what I have so far and do not understand how to output using ctime to calculate how long the loop takes and display the result and time required to calculate the loop.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "stdafx.h"
#include <iomanip>
#include <iostream>
#include <ctime>
using namespace std;


int main(void)
{ 
int dummy;


clock_t starttime, end;
double msecs;
int fsumfloat;



for (int i = 1; i <= 10000000; i++) {fsumfloat + = 1.0 / i;}
starttime = clock();
end = clock();
msecs = ((double)clock()-starttime) / CLOCKS_PER_SEC; 
cout << fixed << endl;


cin >> dummy;
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <ctime>
using namespace std;


int main(void)
{ 

clock_t starttime, end;
double secs;
double fsumfloat=0;
long i;


starttime = clock();
for (i = 1; i <= 10000000L; i++) 
{
fsumfloat += (1.0 / i);
}

end = clock();
secs = ((double)(end-starttime)) / CLOCKS_PER_SEC; 
cout << secs << endl<<fsumfloat<<endl<<i<<endl;
}

A few things to notice:
1. starttime has to be before the loop
2. convert to double the difference between starttime and end
3. CLOCKS_PER_SEC implies that your answer will be in seconds, not miliseconds
Thank you for the help ats15.
Topic archived. No new replies allowed.