1

I have a piece of code in C++. My question would be how can one return 1.5 as a result instead of 1 from the following code.

double avg(int, int);
int main ()
{
    double average= avg(2, 1);
    cout << average;
}

double avg(int num1, int num2)
{
    double average = (num1 + num2)/2;
    return average;
}
jenny
  • 450
  • 6
  • 19

1 Answers1

4

Just make at least one of them a double:

 double average = (num1 + num2)/2.0; // note 2.0 is a double

This will allow implicit conversion to happen and convert everything to a double.