Search code examples
c++mathpearson

Error in displaying the largest and smallest number


I was attempting to write a program for exercise 2.19 in How to Program, but I ran into some difficulties.

The program is supposed to have the user enter three integers and then display the sum, average, and product of those integers.

The only problem I am having is with displaying the largest and smallest. When I ran the program and entered three integers (8, 9, and 10), the output read Smallest is 8 AND Smallest is 9.

I was hoping you could tell me why.

#include <iostream>
using namespace std;

int main ()
{   int x, y, z, sum, ave, prod;

    cout << "Input three different integers ";
    cin >> x >> y >> z;

    sum = x + y + z;
    cout << "\nThe sum is " << sum;

    ave = (x + y + z) / 3;
    cout << "\nThe average is " << ave;

    prod = x * y * z;
    cout << "\nThe product is " << prod;

    if (x < y, x < z)
      {cout << "\nSmallest is " << x;}

    if (y < x, y < z)
      {cout << "\nSmallest is " << y;}

    if (z < x, z < y)
      {cout << "\nSmallest is " << z;}

    if (x > y, x > z)
      {cout << "\nLargest is " << x << endl;}

    if (y > x, y > z)
      {cout << "\nLargest is " << y << endl;}

    if (z > x, z > y)
      {cout << "\nLargest is " << z << endl;}

    return 0;
}

P.S. I am doing this to study, this is not homework.


Solution

  • You need to rewrite this if condition

    if (x < y, x < z)
    

    to be

    if (x < y && x < z)
    

    and do the same for all of the remaining if conditions you have.

    Edit: All experssions seperated by comma will be evaluated so if you have something like that x = 5, y = 6; it will evaluate both of them and set x to 5 and y to 6 but z = (x=5, y=6); this will cause z to be set to 6 just like y as y=6 was the last term in the list of comma separated terms.