C++ Function Problem?

Hey y'all

I am having a curious problem with a function I wrote.

Here it is.

#include <iostream>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;


int sum1 (int);
int main ( )

{

int n = 5;
int sumone;

cout << "The value of sum1 is " << sumone << endl;


system("Pause");
return 0;
}

int sum1 (int )
{
int n;

int sumone = 0;
int k = 1;

for (k = 1; k <= n; k++)

sumone += k * k * k;

return sumone;
}


For some reason, sumone is being returned as

The value of sum1 is 2621256
Press any key to continue . . .


I assume I am missing something very basic, but I just don't know what.
1
2
3
4
int sum1 (int ) // <- this int is the one you want to use, but you didn't give it a name
{
int n;  // <- instead you are using this int, which you never assigned any value to
//  so it will be random garbage 



You probably meant to do this:

1
2
3
int sum1(int n)  // <- n is the passed parameter
{
//int n;  <- get rid of this 



Also, you are never actually calling your sum1 function, so that code will never be executed anyway.

1
2
3
4
int n = 5;
int sumone;  // <- this variable is never initialized

cout << "The value of sum1 is " << sumone << endl;  // <- so what do you expect this to print? 


You will need to actually call your function in order for the code inside it to be run. You want to assign whatever the function outputs to your sumone variable. That will look like this:

 
sumone = sum1( n );
You are amazing, thank you!!!
Topic archived. No new replies allowed.