不使用'-'运算符减去两个数字 [英] Subtracting two numbers without using '-' operator

查看:62
本文介绍了不使用'-'运算符减去两个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码,但是我不明白为什么它给了我错误的答案.我正在计算2的补码,并加上另一个数字.

i tried with the following code , but i can't understand why it's giving me wrong answer. i am computing the 2's complement and adding with another no.

#include <stdio.h>

int add(int a, int b) {
    while (a) {
        a = (a & b) << 1;
        b = a^b;
    }
    return b;
}

int sub(int a, int b) // add a with b's 2's complement.
{
    return (add(a, add(~b, 1)));
}

int main() {
    int a, b, res;
    a = 3, b = 1;
    res = sub(a, b);
    printf("%d\n", res);
    return 0;
}

推荐答案

我使用了NullUserException建议的其他add()函数,现在可以使用:

i used a different add() function as suggested by NullUserException, it works now:

int add(int a,int b)
{
  int x;
  x = a^b;

  while(a&b)
  {
    b = ((a&b)<<1);
    a = x;
    x = a^b;
    //b=(a^b);
  }

  return x;
}

这篇关于不使用'-'运算符减去两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆