Skip to main content

4.4) Exercise 6


Write a program that averages two numbers input by the user. Your program should:

  • Define double variables x and y to hold the numbers
  • Prompt the user in an appropriate way and then read values from cin into x and y
  • Compute the average using the expression (x + y) / 2, storing the result in a double variable called average
  • Display the value of average

Compile the program and run it several times, using different pairs of values for x and y, until you are happy that it behaves correctly.

Now change the type of x and y to int, leaving the rest of the program unchanged. Recompile the program and run it several times, as you did before. How does its behaviour change?

The root of the problem is that division of an integer (the result of x + y) by an integer yields another integer, rather than the required floating-point result. You can fix this either by applying an explicit cast to (x + y) or by changing the 2 in the expression to 2.0, forcing implicit type conversion. Make either of these changes, then recompile and rerun the program to verify that the problem has been fixed.