1.12.2.Use static variable to compute a running average of numbers entered by the user
#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