Hello everyone!
I'm new to C++ and have a problem with exercise 3.6 from Scheinerman's
C++ for mathematicians. The exercise asks me to write a programm that, given a (strictly) positive integer N as input, computes the Sum 1 + 1/(2^2) + ... + 1/(N^2). (The exercise asks for more, but this is the part where I run into problems).
This is what I did:
The header of the programm sum1:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#ifndef SUM1_H
#define SUM1_H
/**
* A programm to calculate the the sum of 1/(k^2) from 1 to N for a
* given integer N, starting with 1/N^2 and then going down to 1/1^2.
* @param positive integer N
* @return The sum named above as float
*/
float sum1(int n);
#endif
|
The code of sum1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
#include "sum1.h"
using namespace std;
float sum1(int n) {
float a = 0;
if (n <= 0) a = a;
else {//in case n > 0:
int m;
for(m = n; m >= 1; m--) {
a += 1/(float(m^2));//a = a + 1/(float(m^2));
}
return a;
}
}
|
And this is the file for testing it:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
#include "sum1.h"
using namespace std;
int main() {
int n;
cout << "An integer, please!" << endl;
cin >> n;
cout << "1 + 1/(2^2) + ... + 1/(" << n << "^2)"
<< " = " << sum1(n) << "." << endl;
return 0;
}
|
I do not get any errors when compiling (I use the GNU compiler, my OS is Linux), but this is the output of it:
If I run it with a nonpositive integer as input (in this case -13), the ouput is
1 + 1/(2^2) + ... + 1/(-13^2) = nan.
|
,
If the input is 1, the output is
1 + 1/(2^2) + ... + 1/(1^2) = 0.333333.
|
,
and if the input i strictly positive (in this case 12), the ouput is
1 + 1/(2^2) + ... + 1/(12^2) = inf. |
.
I have no idea what might cause this.
Best regards, Faltoup