• Advertisement
Sign in to follow this  

Maintain a running total

This topic is 2658 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;
}

Share this post


Link to post
Share on other sites
Advertisement
If you want a variable to keep its value between calls to a function, declare that variable as static.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement