The goal here is to use pass by value to calculate sum of (1/n)^2 aka: (1/1)^2 + (1/2)^2 +... (1/n)^2.
Im a beginner and so far i cannot understand what is wrong with my code.. I just keep on getting a blank result after my first output line
#include "stdafx.h"
#include <iostream>
#include <cmath>
usingnamespace std;
double sum2(unsignedint);
unsignedint getValidPositiveInteger();
int main()
{
unsignedint i = getValidPositiveInteger();
cout << "Enter the number of terms in the partial sum approximation of the series (n): \n";
cin >> i;
cout << "Using pass by value, the partial term using " << i << " terms is: " << sum2(i);
return 0;
}
double sum2(unsignedint n)
{
double sum = 0, result;
unsignedint a;
for (a = 1; a <= n; ++a)
{
result = pow((1.0/a), 2);
sum += result;
}
return (sum);
}
// 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;
}
1. Why does line 23 call getValidPositiveInteger()?
2. Your main() has aqcuired a value "i" and given it to function sum2(). The sum2() thus has the given value in "n". What is the first thing you do in that function?
You do n = 1;. So long for the value gotten from the caller. Perhaps your loop should use a different variable?
3. 1 / n. That has integer (1) and unsigned int (n). Integer division. Integer division returns an integer. 1/1 returns 1. 1/n, where n>1, returns 0.
1.0 / n has double and unsigned int. There are no mixed operators. A double/double will be used and that produces a double.
#include <iostream>
int foo( int n ) {
int sum = 0;
for ( int y = 1; y <= n; ++y ) {
sum += y;
}
return sum;
}
int main() {
int count = 3;
int result = foo( count );
std::cout << "1+2+3=" << result << '\n';
return 0;
}
I understood it all. What was bugging me was that I was not getting it that when I gave my sum2() the value i; the value n was being assigned that same value i.