如何在不使用任何标准运算符(如 *,-,/,% 等)的情况下将数字与 3.5 相乘
How to multiply a number with 3.5 without using any standard operator like *,-,/,% etc?
这个问题很简单。我得到一个数字,我想将其乘以 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;
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在没有信号的情况下从C++执行QML插槽
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 为什么在某些情况下不写入此文件?
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 在没有Xcode的情况下在Mac捆绑包中嵌入框架
- UE4-如何在给定4个屏幕坐标的情况下缩放纹理或材质
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 在C++中如何在没有pow的情况下进行基础计算
- 松弛原子与无同步情况下的记忆连贯性
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在不使用 * 和 / 运算符的情况下将两个浮点数相乘和除以
- 如何在不使用任何标准运算符(如 *,-,/,% 等)的情况下将数字与 3.5 相乘