Double Check This Please!

December 14, 2009 at 14:29:01
Specs: Windows XP
#include <iostream.h>
void main()
{
int i ;
int j ;
cout << "Enter the first integer: " << endl ;
cin >> i ;
cout << "Enter the second integer: " << endl ;
cin >> j ;
if( i == j )
cout << "The numbers are equal." << endl ;
if( i < j )
cout << i << " is less than " << j << endl ;
else
cout << j << " is less than " << i << endl ;
}
//


This needs to work with the numbers being the same or different but it doesn't. What am I doing wrong? All help greatly appreciated!


See More: Double Check This Please!

Report •


#1
December 14, 2009 at 18:06:33
my attempt worked when you put the whole second "if/else" block inside of "else" (immed. after "cout the numbers are equal"). doesn't look very good as code but it works.

Report •

#2
December 14, 2009 at 18:19:34
You should be returning a value from function main

int main(void) { ... return (0); // if no error occured }

It doesn't work as expected because your test isn't quite right. You're checking if they're equal and then again if one is greater than the other. One test is all you'll need.

if(i == j) {
cout << "equal";
} else if(i > j) {
cout << "i > j";
} else {
cout << "j > i";
}

or simply

cout << (i == j ? "they're equal" : i > j ? "i is greater" : "j is greater");

As a side note, your program is somewhat dangerous if bad input is entered. For example, a user inputs a character, punct, or symbol. At minimum, you might consider using assert.h to make sure cin hasn't failed.

#include <cassert>
or
#include <assert.h>

cout << "enter i: ";
cin >> i
assert(cin.good());

cout << "enter j: ";
cin >> j
assert(cin.good());

HTH


Report •

#3
December 15, 2009 at 06:35:46
#include <iostream>
using namespace std;

int main(void); 
{
int i ;
int j ;
cout << "Enter the first integer: " << endl ;
cin >> i ;
cout << "Enter the second integer: " << endl ;
cin >> j ;
if(i == j) {
cout << "equal";
} else if(i > j) {
cout << "i > j";
} else {
cout << "j > i";
}


This is what I have came up with, but I am still getting errors. What am I doing wrong? HELP!!!


Report •

Related Solutions

#4
December 15, 2009 at 07:41:44
Left out a closing brace at the end of the file. Was the error message unclear?

Report •

#5
December 17, 2009 at 05:40:37
shutat: you might consider using assert.h to make sure cin hasn't failed.
Careful; assert() only exists in debug builds of applications.

PammyA: What am I doing wrong? HELP!!!
Not following proper indentation guidelines, for one. If you were, you'd notice you need another '}' to close your main().


Report •


Ask Question