0

My program is returning a value of the score array instead of the average. I am guessing the problem has to do with the type conversions.

#include <iostream>
using namespace std;

float average(int length, int array[]);

int main(){
    int N;
    
    cout << "Enter length: ";
    cin >> N;
    cout << endl;
    int scores[N];
    for(int i = 0; i < N; i++){
        cout << "Enter score: ";
        cin >> scores[i];
    }
    
    cout << average(N, scores);
    return 0;   
}

float average(int length, int array[]){
    int sum = 0;
    for(int i = 0; i < length; i++){
        sum += array[i];
    }
    
    return (sum / length);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • It would help if you described the problem you are facing. At first glance I'm assuming your issue is that you are losing the fractional part due to `sum / length` being an integer – Human-Compiler Aug 25 '21 at 00:40
  • 1
    On a side note: `int N; ... int scores[N];` is [not standard C++](https://stackoverflow.com/questions/1887097/). Use `std::vector` instead. – Remy Lebeau Aug 25 '21 at 00:59

1 Answers1

4

When you divide the integer sum by the integer length, you get an integer result. The fact that you store it in a float doesn't change that.

You probably want:

return (static_cast<float>(sum) / static_cast<float>(length));
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Re ”if they also took into account how you used the result, they'd be incomprehensible”: `int x = f;` and `float x = f;` produce different values if `f` is defined as `foo f;` where `foo` is `struct foo { operator int() { return 3; } operator float() { return 4; } };`. – Eric Postpischil Aug 25 '21 at 13:38