Negative digit...

hello everyone i write a program that seperate digits of the logged number but when the number is negative it's not work...
old code:
int _tmain(int argc, _TCHAR* argv[])
{
int x,y,z;
cout << "Please enter a number" << endl;
cin >> x;
y = x % 10;
cout<< y << endl;
z = x / 10;
cout<< z << endl;
getch();
return 0;
}
i solve it by this code:
int _tmain(int argc, _TCHAR* argv[])
{
int x,y,z;
cout << "Please enter a number" << endl;
cin >> x;
y = -x % 10;
cout<< y << endl;
z = x / 10;
cout<< z << endl;
getch();
return 0;
}
i want to understand when user enter a negative number
why the compiler output result is two negative digit in the old code?
why the compiler output result is two negative digit in the old code

Why do you expect a different outcome? y % 10 does not mean "the rightmost digit of y", it means "the remainder of the division of y by 10, rounded towards zero1". It's a mathematical operation, not a string-of-digits operation. -123 / 10 gives -12, -123 % 10 gives -3, so that you can multiply -12 by 10, add the remainder (-3) and get your original number (-123) back.

1technically, this was implementation-defined behavior until c99/c++11
Last edited on
Actually mathematics usually defines remainder as non-negative number (another version exists but some formulas stop working for negative numbers in that case) Usually (-7 / 5) is -2 with remainder 3.
But in computer science these two operations (division and modulus) can behave either way/ You should lear, how is it working on your language/platform.

non-negative remainder (x%y): (x % y) + y) % y)
Even Matlab defines remainder as negative in this case. Although, yes, for each programming language, it's important to look up how these operations are defined, to see if a function that obtains the rightmost digit of an integer can be constructed from them.
Wolfram Mathematica thinks it is positive :)
As I say there is two systems. Maybe default system is different depending on country, like metric and imperial systems of measurement.
Topic archived. No new replies allowed.