Maintain a running total

Started by
1 comment, last by MikeWhiskyTango 13 years, 6 months ago
Im not sure how to have the function maintain a running total.
In my example it does not give the total score, but each time
runtot function is called it resets the total.


#include <iostream>
#include<ctime>
using namespace std;

int runtot (int subtot = 0);

int main()
{
srand (time(NULL));
int random = (rand()%10);
cout<<random<<" \n";
runtot (random);


int randm = (rand()%10);
cout<<randm<<" \n";
runtot (randm);

int total = runtot ();
cout<<total; //I want this to print out the running total of runtot()

system("pause");
return 0;
}

int runtot (int subtot)
{
int change = 0;
change += subtot; //I want the variable change to maintain a running total in this function
cout<<change<<" \n";

return change;
}
Advertisement
If you want a variable to keep its value between calls to a function, declare that variable as static.
Excellent thank you.

This topic is closed to new replies.

Advertisement