仅具有特定方法的计算器。正常和递归

扬·菲舍尔

所以 atm 我一直在用我的计算器。只允许使用以下方法:

int succ(int x){
    return ++x;
}



int neg(int x){
    return -x;
}

我已经得到的是+,-。*. 迭代也是递归的(所以我也可以在需要时使用它们)。现在我坚持使用除法方法,因为我不知道如何处理逗号及其背后的逻辑。想象一下处理 succ() 和 neg() 的样子,这里有一个减法迭代和递归的例子:

int sub(int x, int y){
    if (y > 0){
        y = neg(y);
        x = add(x, y);
        return x;
    }
    else if (y < 0){
        y = neg(y);
        x = add(x, y);
        return x;
    }
    else if (y == 0) {
        return x;
    }
   }

int sub_recc(int x, int y){
    if (y < 0){
        y = neg(y);
        x = add_recc(x, y);
        return x;
    } else if (y > 0){
        x = sub_recc(x, y - 1); 
        x = x - 1;
        return x;
    }else if( y == 0) {
        return x;
    }
}
塞尔吉·巴列斯塔

如果您可以进行减法和加法,那么您就可以处理整数除法。在伪代码中,它只是:

division y/x is:
   First handle signs because we will only divide positive integers
   set sign = 0
   if y > 0 then y = neg(y), sign = 1 - sign
   if x > 0 then y = neg(y), sign = 1 - sign
   ok, if sign is 0 nothing to do, if sign is 1, we will negate the result

   Now the quotient is just the number of times you can substract the divisor:
   set quotient = 0
   while y > x do
       y = y - x
       quotient = quotient + 1
   Ok we have the absolute value of the quotient, now for the sign:
   if sign == 1, then quotient = neg(quotient)

C++ 语言中的正确翻译以及递归部分留作练习...

提示递归 y/x == 1 + (yx)/x 而 y>x


以上是整数部分。Integer 很好也很简单,因为它提供了精确的操作。基数中的浮点表示总是接近尾数 * 基数exp,其中尾数是具有最大位数的整数或介于 0 和 1 之间的数字(即正常表示)。并且您可以从一种表示传递到另一种表示,但通过尾数的位数更改指数部分:2.5 是 25 10 -1 (int 尾数) of .25 10 1 (0 <= 尾数 < 1)。

因此,如果您想操作基数为 10 的浮点数,您应该:

  • 将整数转换为浮点数(尾数 + 指数)表示
  • 对于加法和减法,结果指数是指数中较大的一个先验两个尾数都应缩放到该指数并相加/相减。然后必须调整最终指数,因为该操作可能添加了一个额外的数字 (7 + 9 = 16) 或导致最高阶数字消失 (101 - 98 - 3)
  • 对于乘积,您将指数相加并乘以尾数,然后对结果进行归一化(调整指数)
  • 对于除法,您可以按最大位数缩放尾数,使用整数除法算法进行除法,然后再次归一化。例如,精度为 6 位的 1/3 可通过以下公式获得: 1/3 = (1 * 10 6 /3) * 10 -6 = (1000000/3) * 10 -6

以标准化形式给出 333333 * 10 -6所以 .333333

好吧,这将是很多沸腾的板代码,但没有什么很难的。

日志故事简短:只要记住你是如何用纸和铅笔学到的......

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章