This was the third or fourth time that encounter this problem and it just annoys me because it makes no sense for me as beginner programmer.
So for my class I had to make a program(function inside a program) that will find largest and smallest digit in a number and return the digit count as a variable. I hate to use references but thats not the point right now.
My program works well, as expected nothing bad is happening until I try to send the largest long long int number to the function.
Because I don't need a negative number inside my function I used an if statment to check if number is <0 and if it is then it should be multiplied by -1 to get a positive(I know that I could use the abs function but same result).
When I pass the largest long long int which is −9,223,372,036,854,775,807 program returns that the number is smaller than 0 but also returns a negative number, not a positive one, but when I test the −9,223,372,036,854,775,807 which is that number -1 everything works again.
So my question is what is actually happening here, why is the n*=-1 part ignored, is it because the number is using all of the memory or ?
int Digits(long long int n,int &c_min,int &c_max){
c_min=9;
c_max=0;
if(n<0){
n*=-1;
}
int digit;
int numberOfDigits(0);
while(n!=0){
digit=n%10;
if(digit > c_max) c_max=digit;
if(digit< c_min) c_min=digit;
numberOfDigits++;
n/=10;
}
if(numberOfDigits==0){
c_min=0;
c_max=0;
return 1;
}
return numberOfDigits;
}
MAIN FUNCTION :
int main ()
{
int mini,maxi;
int e = Digits(std::numeric_limits<long long int>::min(), mini, maxi);
std::cout << e;
return 0;
}