i am getting result of average in int instead of float, tell me where i have made mistake. this is the code.

#include<iostream>
using namespace std;

void getData (int a[], int s);
int numbersSum (int a[], int s);
float average (int sum, int size);

int main()
{
int size=0;
int a[size];
cout<<"how many numbers: "<<endl;
cin>>size;
cout<<"Enter "<<size<<" numbers:"<<endl;

getData (a, size);


int sum=0;
sum=numbersSum (a, size);
cout<<"sum of these "<<size<<" numbers is "<<sum<<endl;


float avg=0;
avg=average (sum, size);
cout<<"the average of these "<<size<<" numbers is "<<avg<<endl;

    return 0;
}

void getData(int a[], int s)
{
    for (int i=0;i<s;i++)
    {
        cin>>a[i];
    }
}

int numbersSum (int a[], int s)
{
    int sum=0;
    for (int i=0;i<s;i++)
        sum=sum+a[i];

    return sum;

}

float average (int sum, int size)
{
    float a=sum/size;
    return a;
}

You just need to cast sum as type float.

float average (int sum, int size)
{
    return static_cast<float>(sum) / size;
}

You can also multiply sum by 1.0 to turn it into a float ...

float average (int sum, int size)
{
    float a=1.0*sum/size;
    return a;
}

int size=0;
int a[size];

That creates an array of 0 elements. That's not what you want. Move line 11 down to below line 13 where the value of size is known. Note: you will have to use a c++11 compliant compiler to compile this.

Edited 3 Years Ago by Ancient Dragon

This article has been dead for over six months. Start a new discussion instead.