Iterating with arrays

Mar 15, 2015 at 11:41pm
The problem wants me to print the average as well as the sum.

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

#include <iostream>
using namespace std;

int main() {
   const int NUM_ELEMENTS = 8; // Number of elements
   int userVals[NUM_ELEMENTS]; // User numbers
   int i = 0;                  // Loop index
   int sumVal = 0;             // For computing sum
    int avg = 0;                // For computinng average
   
   // Prompt user to populate array
   cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;

   for (i = 0; i <= NUM_ELEMENTS; ++i) {
      cout << "Value: " << endl;
      cin >> userVals[i];
   }
   
   // Determine sum
   sumVal = 0;
   
   for (i = 0; i < NUM_ELEMENTS; ++i) {
      sumVal = sumVal + userVals[i];
   }
   
   cout << "Sum: " << sumVal << endl;
   
   // Determine average and Where I added
   avg = 0;
  
   for (i = 0; i < NUM_ELEMENTS; ++i){
       avg = sumVal / NUM_ELEMENTS;
   }
   cout << "Average: " << avg << endl;
   
   return 0;
}
Mar 15, 2015 at 11:47pm
First, the loop is unnecessary; the result of sumVal / NUM_ELEMENTS remains the same no matter how many times you do it.

The real problem, however, is that that division does integer math and integer division discards remainder. You have to force floating point math, unless you really want integer math.

You force with explicit cast: static_cast<double>(sumVal) / NUM_ELEMENTS

The variable 'avg' obviously shoudn't be int either.
Topic archived. No new replies allowed.