Did I do this right!? :D

Jul 21, 2012 at 8:40am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*Ask the user to enter an integer and tell whether if its positive or negative*/
#include <iostream>

using namespace std;

int main()
{
int num;

cout << "Enter an integer!" << endl;
cin >> num;

if ( 0 < num )
    cout << "The integer is positive!" << endl;
else
    cout << "The integer is negative!" << endl;

    return 0;
}


Jul 21, 2012 at 8:42am
closed account (o3hC5Di1)
Hi there,

If your program compiles - and it works as you expect it to, that's about the biggest "yes, you did it right" you can get :)

All the best,
NwN
Jul 21, 2012 at 8:46am
Do you consider 0 to be negative?
Last edited on Jul 21, 2012 at 8:54am
Jul 21, 2012 at 8:55am
you did nothing wrong it should work fine..
0 is nether positive nor negative.
Jul 21, 2012 at 12:45pm
True, it's neither positive or negative. But if a user is to enter 0, the program will just quit. It should at least print something like "The integer is zero".
Jul 21, 2012 at 2:16pm
Maybe this is what you want. on original code 0 was considered as negative.

1
2
3
4
5
6
if ( 0 < num )
    cout << "The integer is positive!" << endl;
else if (0 > num)
    cout << "The integer is negative!" << endl;
else
    cout << "The integer is 0!" << endl;
Jul 21, 2012 at 2:17pm
True, it's neither positive or negative. But if a user is to enter 0, the program will just quit. It should at least print something like "The integer is zero".

not in your code above...
Last edited on Jul 21, 2012 at 2:17pm
Jul 21, 2012 at 10:03pm

Maybe this is what you want. on original code 0 was considered as negative.





1
2
3
4
5
6
if ( 0 < num )
    cout << "The integer is positive!" << endl;
else if (0 > num)
    cout << "The integer is negative!" << endl;
else
    cout << "The integer is 0!" << endl;








Oh... I should done it that way XD
Last edited on Jul 21, 2012 at 10:04pm
Jul 21, 2012 at 10:45pm
Okay, this is for me but it's slightly relevant:

When using conditionals, should I compare the relevant variable or whatnot by writing it first in the statement?
ie:
if(relevantVar >= otherNum)

Or is it just personal preference?
Jul 22, 2012 at 1:06am
maybe what you mean is the order of the variable like it has to write first? afterall, the if statement execute the true result inside the parentheses, so the order of the writing is not relevant (afaik). e.g.:

 
if (1 >= relevantVar) //if relevantVar is -3, then this statement is true 


or

 
if (relevantVar <= 1) //either... 


hope that help
Jul 22, 2012 at 2:07am
I know that both will evaluate in the same way, what I'm wondering is whether there is any standard, such as with indentation.
Topic archived. No new replies allowed.