Static Variable

Write a function called QuizPoints(int value) that contains two static variables. One that stores the number of quizzes taken and one that stores the total points earned on all quizzes. The main function should use a do or while loop to query the user to enter quiz grades with values between 0 and 20. This values should be passed to the function which then prints the quiz grade to the console every time it is called.

This is what I have so far and I believe I am far from the answer. Any suggestions?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cmath>

using namespace std;

void Quiz(float iGrade)
{	float i = 1;
	static float iTotal = 0.0;
	static int iNumQ = ++i;


	
	if(iNumQ <= 1)
	{
		iTotal = iGrade*1;
	}
	else
	{
	iTotal = (iGrade+iTotal)/2;	
	}
	

	cout << "THE AVERAGE: " << iTotal << " NUMBER OF QUIZ: " << iNumQ << endl;
	
}
	
int main (void)
{
	float iGrade = 0.0;
do
{

	cout << "PLEASE ENTER QUIZ GRADE" << endl;
	cin >> iGrade;
	
	Quiz(iGrade);
	
}
while(iGrade > -1);

	return 1;
}
Write a function called QuizPoints(int value)
void Quiz(float iGrade)

Well, you've written a function called Quiz that takes a float called iGrade, where the instructions are to write one called QuizPoints that takes an int called value.
From what I see, your main problem is that you haven't understood how to initialize your static variables.

It's very simple.
The trick is to understand that since the variables are static, they are supposed to keep their values between function calls. Therefore they cannot and will not be reset to their initialization values (otherwise they'd be useless).

In fact, the initialization values will be used only the first time the function is called.
Every subsequent call of the function will behave as if the initialization code was not there.

Since you want to use your static variables as accumulators, their starting value should be 0. The code to initialize them is:
1
2
static float iTotal = 0;
static int iNumQ = 0;

And nothing else !

Now, all you have to do is to write the code to accumulate the values.
It's pretty simple: when the function is called, add iGrade to iTotal and add 1 to iNumQ.
I think you can do it by yourself.


Topic archived. No new replies allowed.