Hello! The goal here is to get the sum of (1/n)^2 aka: (1/1)^2 + (1/2)^2 +...(1/n)^2.
Im using pass by reference to try to get the task done but I keep on getting a wrong result. Can somebody help me pinpoint my errors please.
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
#include <cmath>
usingnamespace std;
void sum1(double&, unsignedint); //This string was given
unsignedint getValidPositiveInteger();
int main()
{
unsignedint i = getValidPositiveInteger();
double sum;
cout << "Enter the number of terms in the partial sum approximation of the series (n): \n";
cin >> i;
sum1(sum, i);
cout << i << " " << sum << endl;
return 0;
}
void sum1(double& sum, unsignedint n)
{
unsignedint c;
for (c = 1; c <= n; ++c)
{
sum += (1.0 / c)*(1.0 / c);
}
}
// Get a valid integer from the user
unsignedint getValidPositiveInteger() {
int userInput;
cin >> userInput;
while (cin.fail() || userInput < 0) {
cin.clear();
cin.ignore();
cout << "Please enter a positive integer only\n";
cin >> userInput;
}
return userInput;
}
Line 15: sum isn't initialized - and it should be, to zero.
You should get into the habit of compiling with all warnings on - most modern compilers would have warned you about the use of an uninitialized value, which is undefined behavior.