-
Simple Program help.
Objective:
Write a program that inputs three integers from the keyboard and prints the sum, average, product, smallest and largest of these numbers.
Code:
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int a,b,c,sum, product,average,small,large;
cout <<"Enter Three Numbers " <<endl;
cin >>a;
cin >>b;
cin >>c;
sum = a + b + c;
cout <<"The sum is equal to " <<sum <<endl;
average = sum / 3;
cout <<"The average is qual to "<<average <<endl;
product = a*b*c;
cout <<"The product is equal to "<<product <<endl;
if (a > b && c)
cout <<"The largest number is "<<a <<endl;
if (a < b && c)
cout <<"The smallest number is "<<a <<endl;
if (b > a && c)
cout <<"The largest number is "<<b <<endl;
if (b < a && c)
cout <<" is The smallest number is "<<b <<endl;
if (c > b && a)
cout <<"The largest number is "<<c <<endl;
if (c < b && a)
cout <<" is The smallest number is "<<c <<endl;
if (a == b && a == c && b == c)
cout <<"All numbers are equal to each other" <<endl;
cin >>a;
return 0;
}
The problem is that some times the largest or smallest number is displayed twice. Whats the problem and how do I fix it? Im guessing its a simple logic error?
-
>> if (a > b && c)
that's not how the logical AND operator works. suppose you meant:
if (a > b && a > c)
-
-
The program would flow better if the comparison logic was separated into individual functions. As it is, you just need to specify the second case in the conditional statement. Stating "&& c" for example will always be true unless c is equal to 0.
Code:
if (a > b && a > c)
cout <<"The largest number is "<<a <<endl;
if (a < b && a < c)
cout <<"The smallest number is "<<a <<endl;
if (b > a && b > c)
cout <<"The largest number is "<<b <<endl;
if (b < a && b < c)
cout <<" is The smallest number is "<<b <<endl;
if (c > b && c > a)
cout <<"The largest number is "<<c <<endl;
if (c < b && c < a)
cout <<" is The smallest number is "<<c <<endl;
if (a == b && a == c)
cout <<"All numbers are equal to each other" <<endl;
David
** Late on the response.