Use static variable to compute a running average of numbers entered by the user : static « Language Basics « C++ Tutorial






#include <iostream> 
using namespace std; 
 
int f(int i); 
 
int main() 
{ 
  int num; 
 
  do { 
    cout << "Enter numbers (-1 to quit): "; 
    cin >> num; 
    if(num != -1) 
      cout << "average is: " << f(num) << "\n"; 
    
  } while(num > -1); 
 
  return 0; 
} 
 
int f(int i) 
{ 
  static int sum = 0, count = 0; 
 
  sum = sum + i; 
 
  count++; 
 
  return sum / count; 
}
Enter numbers (-1 to quit): 1
average is: 1
Enter numbers (-1 to quit): 2
average is: 1
Enter numbers (-1 to quit): 3
average is: 2
Enter numbers (-1 to quit): 2
average is: 2
Enter numbers (-1 to quit): 1
average is: 1
Enter numbers (-1 to quit): 2
average is: 1
Enter numbers (-1 to quit): 3
average is: 2
Enter numbers (-1 to quit): -1








1.12.static
1.12.1.Using a static long variable
1.12.2.Use static variable to compute a running average of numbers entered by the user
1.12.3.Initialize static member field outside the class declaration
1.12.4.A static local variable causes the compiler to create permanent storage for it in much the same way that it does for a global variable.