Can someone explain why I get this number?

Running my code I get a number close to -8 million or so.. I'm sure it's not supposed to be that small, in fact it should be between 0 and 100.



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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
  #include <iostream>
#include <string>

using namespace std;


void getStudentName(string &first, string &last);
void getNumberExams(int &examstaken);
void getScoresandCalculateTotal(int &scores);
void calculateAverage();
void determineLetterGrade();
float displayAverage();

int exam;

int main()
{
	string first, last;
	
	int total;
	
	
	getStudentName(first, last);
	cout << first << " " << last << endl;
	getNumberExams(exam);
	getScoresandCalculateTotal(total);
	cout << "Your total is: " << total << endl;

}

void getStudentName(string &a, string &b)
{ 
	string first, last;
	cout << "Hello! Please enter your first name: " << endl;
	cin >> first;
	cout << "And your last name?" << endl;
	cin >> last;

	cout << "Hey " << first << " " << last << "!" << endl;
}

void getNumberExams(int &exams)
{
	int exam;
	cout << "How many exams have you taken? " << endl;
	cin >> exam;
	if (exam > 0)
		cout << "You've taken " << exam << " exams. That's great!" << endl;
	while (exam <= 0)
	{
		cout << "That can't be right! Please put in the number of exams you have taken: " << endl;
	cin >> exam;
	}
	
}

void getScoresandCalculateTotal(int &total)
{
	int totals = 0;
	int score = 0;
	int takenexams = 0;
	
	while (takenexams <= exam)
	{

		cout << "Enter your exam score" << endl;
		cin >> score;
		takenexams++;
		totals += score;
	}
		

}

Line 63, what is the value of exam?
I took int exam out on line 44 since exam is a global variable but it's value is given in the second function. Now it's asking for one more exam score than the given number and then displaying the -8 million again.
Last edited on
Same problem at line 59. The caller is expecting you to update the parameter (total) but you're actually updating a local variable (totals)
Well I moved the total variable to a global scope and it worked. Thanks for all of the responses!
Congratulations!

Now you might want to make the code even better by having getScoresAndCalculateTotal() and getNumberExams() return their respective values. Then you can make exam a local var. In otherwords, change the functions so that main() looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
	string first, last;
	int exam, total;

	getStudentName(first, last);
	cout << first << " " << last << endl;
	exam = getNumberExams();
	total = getScoresandCalculateTotal();
	cout << "Your total is: " << total <<endl;
	return 0;   // I added this. It's good form to return 0 from main on success
}
Topic archived. No new replies allowed.