如何在不使用任何标准运算符(如 *,-,/,% 等)的情况下将数字与 3.5 相乘

How to multiply a number with 3.5 without using any standard operator like *,-,/,% etc?

本文关键字:情况下 相乘 数字 任何 运算符 标准      更新时间:2023-10-16

这个问题很简单。我得到一个数字,我想将其乘以 3.5,即使数字 n=3.5n。我不允许使用任何运算符,例如+,-,*,/,% 等但我可以使用按位运算符

我自己尝试过,但它没有给出精确的结果,就像我的程序为 17 * 5 提供输出 3.5 一样,这显然是错误的。如何修改我的程序以显示正确的结果。

#include<bits/stdc++.h>
using namespace std;
double Multiply(int n)
{
   double ans=((n>>1)+ n + (n<<1));
   return ans;
}
int main()
{
  int n;            // Enter the number you want to multiply with 3.5
  cin>>n;
  double ans=Multiply(n);
  cout<<ans<<"n";
  return 0;
}

对不起,我还不能发表评论。你的问题在于按位运算通常只在整数上完成。这主要是因为数字的存储方式。

当你有一个普通的整数时,你有一个符号位,后面跟着数据位,非常简单明了,但是一旦你到了浮点数,简单的父子就不同了。这是一个很好的解释堆栈溢出。

另外,我在不使用 +/-/*//等情况下解决您的问题的方式是

#include <stdlib.h> /* atoi() */
#include <stdio.h>  /* (f)printf */
#include <assert.h> /* assert() */
int add(int x, int y) {
    int carry = 0;
    int result = 0;
    int i;
    for(i = 0; i < 32; ++i) {
        int a = (x >> i) & 1;
        int b = (y >> i) & 1;
        result |= ((a ^ b) ^ carry) << i;
        carry = (a & b) | (b & carry) | (carry & a);
    }
    return result;
}
int negate(int x) {
    return add(~x, 1);
}
int subtract(int x, int y) {
    return add(x, negate(y));
}
int is_even(int n) {
    return !(n & 1);
}
int divide_by_two(int n) {
    return n >> 1;
}
int multiply_by_two(int n) {
   return n << 1;
}

在您的解决方案中,您可以手动处理奇数:

double Multiply(unsigned int n)
{
   double = n + (n << 1) + (n >> 1) + ((n & 1) ? 0.5 : 0.);
   return ans;
}

但它仍然使用+

一种解决方案是使用 <cmath> 中的fma()

#include <cmath>
double Multiply(int n)
{
    return fma(x, 3.5, 0.0);
}

现场演示

简单地说。

首先意识到 3.5 = 112/32 = (128 - 16)/32。

比你做的:

int x128 = ur_num << 7;
int x16 = ur_num << 4;

要减去它们,请使用:

int add(int x, int y) {
int carry = 0;
int result = 0;
int i;
for(i = 0; i < 32; ++i) {
    int a = (x >> i) & 1;
    int b = (y >> i) & 1;
    result |= ((a ^ b) ^ carry) << i;
    carry = (a & b) | (b & carry) | (carry & a);
}
return result;
}
int negate(int x) {
return add(~x, 1);
}
int subtract(int x, int y) {
return add(x, negate(y));
}

而不仅仅是简单地做:

int your_res = subtract(x128, x16) >> 5;