Subtraction without minus sign in C

后端 未结 17 2003
栀梦
栀梦 2020-12-31 10:26

How can I subtract two integers in C without the - operator?

17条回答
  •  我在风中等你
    2020-12-31 10:44

    Iff:

    1. The Minuend is greater or equal to 0, or
    2. The Subtrahend is greater or equal to 0, or
    3. The Subtrahend and the Minuend are less than 0

    multiply the Minuend by -1 and add the result to the Subtrahend:

    SUB + (MIN * -1)
    

    Else multiply the Minuend by 1 and add the result to the Subtrahend.

    SUB + (MIN * 1)
    

    Example (Try it online):

    #include 
    
    int subtract (int a, int b)
    {
        if ( a >= 0 || b >= 0 || ( a < 0 && b < 0 ) )
        {
            return a + (b * -1);
        }
    
        return a + (b * 1); 
    }
    
    int main (void)
    {
        int x = -1;
        int y = -5;
        printf("%d - %d = %d", x, y, subtract(x, y) );
    }
    

    Output:

    -1 - -5 = 4
    

提交回复
热议问题