Subtraction without minus sign in C

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

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

17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 10:52

    • + No bit setting
    • + Language independent
    • + Can be adjusted for different number types (int, float, etc)
    • - Almost certainly not your C homework answer (which is likely to be about bits)

    Expand a-b:

    a-b = a + (-b)
        = a + (-1).b
    

    Manufacture -1:

    float:             pi = asin(1.0);
    (with    minusone_flt = sin(3.0/2.0*pi);
    math.h)           or  = cos(pi)
                      or  = log10(0.1)
    complex: minusone_cpx = (0,1)**2; // i squared
    integer: minusone_int = 0; minusone_int--; // or convert one of the floats above
    

提交回复
热议问题