Function issues... (not hard to solve hopefully)

My book wants me to make a program that takes in 10 golf scores, displays them, and calculate their mean (all in different functions of course). They also want me to make it possible to terminate input if the user has less than 10 to enter. For some reason, it terminates, but sets the rest of the values at funky numbers.

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

void input(double ar[], int size);
void display(const double ar[], int size);
double mean(const double ar[], int size);

int main(){
    int scores = 10;
    double golf[scores];
    cout << "Enter up to 10 golf scores, and type any letter or word to stop if you don't have anymore to enter\n";
 input(golf,scores);
 display(golf,scores);
 double total = mean(golf,scores);
 cout << " And your average is: " << total << ".";
 cin.get();
    
    
    }
    void input(double ar[], int size){
         int i = 0;
            while (cin && i<size){
          cout << i+1 << ": ";
          cin >> ar[i];
          i++;
          }
          
         }
         void display(const double ar[], int size){
              int i = 0;
              cout << "Here is what you entered for me:\n";
                while (i<size){
          cout << i+1 << ": ";
          cout << ar[i] << "\n";
          i++;
          }
          cin.get();
              }
              double mean(const double ar[], int size){
                     int i = 0;
                     double total = 0;
                while (i<size){
                      total += ar[i];
                       i++;
                  }
                  total /=size;
                  return total;
                  }
              
              
              
try line 10:

 
double golf[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} ;

but sets the rest of the values at funky numbers.

- That's because you don't initialise your array. You've allocated space for 10 numbers, but if the user enters 7 numbers, the last 3 numbers will be set to whatever happens to be in memory at that point. Thus resulting in garbage values.


terminate input if the user has less than 10 to enter
 
void input(double ar[], int size)


- What happens if the user enters 7 numbers?
- Your display function still uses int scores = 10;. Likewise with your mean function.

I would recommend to use std::vector as it's just easier and more convenient to use than arrays.
Last edited on
Topic archived. No new replies allowed.