Vector Help

I need help with my program using vectors. The error comes when you input a decimal. After entering a decimal, the program accepts no input and runs to the end. Also, the average does not output a decimal even if all inputs are integers.

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
  
#include <iostream>
#include <vector>
using namespace std;

std::vector<double> scores (10);

void getScores()
{
	cout << "Enter the scores:\n";
	for (int x = 0; x < 10; x++)
	{
		cout << "Enter Score " << x+1 << ": \n";
		cin >> scores[x];
	}

}

double addVector()
{
	double summ;
	for (int y = 0; y < 9; y++)
	{
		summ += scores[y];
	}
	return summ;
}

double avgVector(double sum)
{
	double avg;
	avg = sum/10;
	return avg;
}

void display(double sum, double avg)
{
	for (int x = 0; x < 10; x++)
	{
		cout << "Score " << x+1 << ": " << scores[x] << endl;
	}
	cout << "Sum: " << sum << endl;
	cout << "Average: " << avg << endl;
}

int main()
{
	double sum;
	double avg;
	getScores();
	sum = addVector();
	avg = avgVector(sum);
	display(sum, avg);
	
	return 0;
}


Here is the output:
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
Enter the scores:
Enter Score 1: 
0.9
Enter Score 2: 
Enter Score 3: 
Enter Score 4: 
Enter Score 5: 
Enter Score 6: 
Enter Score 7: 
Enter Score 8: 
Enter Score 9: 
Enter Score 10: 
Average: 0
Score 1: 0
Score 2: 0
Score 3: 0
Score 4: 0
Score 5: 0
Score 6: 0
Score 7: 0
Score 8: 0
Score 9: 0
Score 10: 0
Sum: 0
Average: 0
Do you have any idea what you floating point precision is set to? Or how strict your compiler is being told to adhere to it? For Microsofts compiler the command line option is "/fp:<fast | precise | strict>". If that is set it could would have an effect on your program as well. I can't think of what the GCC command is.
Last edited on
It looks like the very first cin >> scores[x] is failing. I'm not sure why. It works for me. Maybe cin and cout are linked too tightly? You could try adding cin.clear() before cin >> scores[x].

There are two bugs in addVector(). You need to initialize summ and you aren't adding all the members of the vector.

In both addVector() and display(), I would use scores.size() for the end of the loop so the code will work regardless of the size of the vector. That way if you wanted to change the number of scores, you'd just have to change the code in getScores().
Line 21: summ is uninitialized. Line 24 is going to be adding to garbage.

Line 22: This is only going to add 9 values. scores[9] will not be included.

I tried your program and had no issue entering a variety of doubles.
Topic archived. No new replies allowed.