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

时间:2016-01-19 08:09:24

标签: c++ bit-manipulation bitwise-operators

问题很简单。我给了一个数字,我想将它乘以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;
}

4 个答案:

答案 0 :(得分:1)

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

#include <cmath>

double Multiply(int n)
{
    return fma(x, 3.5, 0.0);
}

LIVE DEMO

答案 1 :(得分:1)

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

当你有一个普通的int时,你有一个符号位后跟数据位,非常简单直接但是一旦你得到浮点数,那么简单的patern是不同的。这是一个很好的解释stackoverflow

此外,我不使用+ / - / * //等解决问题的方法是

#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;
}

Source

答案 2 :(得分:1)

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

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

但它仍然使用+

答案 3 :(得分: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;
相关问题