Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Beginner programming question

Status
Not open for further replies.

fsjcp2

Technical User
Jul 1, 2002
19
US
I'm creating a program that inputs three integers, and returns the sum, product, average, largest and smallest. Very simple, but I'm getting a bad return on one of my variables. Except for my "largest" variable, the others are returning the correct numbers. I'm hoping that someone can tell me where I'm going wrong.


#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
int num1, num2, num3, sum, average, product, smallest, largest;

cout << &quot;Input three different integers: &quot;;
cin >> num1 >> num2 >> num3; // read three integers

sum = num1 + num2 + num3;
average = ( (num1 + num2 + num3) / 3 );
product = num1 * num2 * num3;

if ( num1 < num2 )
smallest = num1;
if ( num2 < num1 )
smallest = num2;
if ( num3 < smallest )
smallest = num3;

if ( num1 > num2 )
largest = num1;
if ( num2 > num1 )
largest = num2;
if ( num3 > largest )
largest = num3;

cout << &quot;\nSum is &quot; << sum;
cout << &quot;\nAverage is &quot; << average;
cout << &quot;\nProduct is &quot; << product;
cout << &quot;\nSmallest is &quot; << smallest;
cout << &quot;\nLargest is &quot; << largest << endl;

return 0; // indicates that program ended successfully
}
 
if ( num1 > num2 )
largest = num1;
else
largest = num2;

if ( num3 > largest )
largest = num3;

Not the most attractive code but it works.
This is assuming that none of the numbers are equal.
 
why the

using std::cout;
using std::cin;
using std::endl;
??
You have enough with iostream.h you know..
-----------------
Why check twice te same? If num1>num2 then you don't have to check if num2 >num1, you already know it is not so.

if ( num1 > num2 )
largest = num1;
else
largest = num2;

if ( num3 > largest )
largest = num3;
-------------------

Enjoy your first steps in programming ;-) Greetz,
muppeteer.gif

NOSPAM_themuppeteer@hotmail.com (for mails, remove the NOSPAM_)

Don't eat yellow snow...and don't mess with your fstab!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top