PDA

Click to See Complete Forum and Search --> : Negative Numbers


SomethinCool
May 29th, 2002, 08:19 AM
i have a as an integer but the output would be -a. does anyone not understand? here..if a user enters 5 the output would be -5. if a user enters -5 the output would be 5. How do i do this using this code:
[code]
#include <iostream.h>

void main()
{
cout << "Enter a: ";
int a;
cin >> a;
if(a == //i have no idea what to put here)
{
//something
}
}

jim mcnamara
May 29th, 2002, 09:23 AM
#include <iostream.h>

void main()
{
int a;
cout << "Enter a: ";
a=0;
cin >> a;
if(a) {
a = a* (-1);
cout << a;
}
return;
}

jim mcnamara
May 29th, 2002, 09:29 AM
#include <iostream.h>

void main()
{
int a;
cout << "Enter a: ";
a=0;
cin >> a;
if(a) {
a = a* (-1);
cout << a;
}
return;
}

Jop
May 29th, 2002, 07:50 PM
hmm why are you multiplying it with -1, is there a special reason for it?
because this also seems to work, or am I overlooking something?

#include <iostream>

using namespace std;

int main(){
int i;
cout << "Enter i" << endl;
cin >> i;
cout << -i << endl;
}

jim mcnamara
May 29th, 2002, 08:59 PM
Yes. if(a) {} should really puke when value is zero.
The 'specs' are a bit scanty to say the least :D

CornedBee
May 31st, 2002, 03:07 AM
unary - operator does exactly that. And for the if(a):
if(cin.good()) {}
checks if cin was able to read a number.