gpt4 book ai didi

c - 按位乘法和除法不适用于大数

转载 作者:行者123 更新时间:2023-11-30 17:05:38 24 4
gpt4 key购买 nike

我试图解决这个问题,我必须乘以 3/8 位,然后四舍五入到零。

到目前为止我已经有了这个

((((x<<1)+x)>>3)+((x>>31)&1));

其背后的想法是,第一部分取 x 并将其左移 1 并添加 x 以获得乘以 3 的效果,然后右移 3 以获得除以 8 的部分。然后,通过测试符号位是否为 1 (1&1 = 1) 或 0 (0&1 = 0),如果为负则加 1。但我的代码无法工作,测试已关闭。

知道我做错了什么吗?

最佳答案

您使用的左移实际上会将各个位作为无符号整数移动,因此您最终可能会丢失符号位。这听起来不像你想要的。尝试乘法,看看你应该得到什么,对比位移看看你会得到什么。

x *= 3.0/8.0;

请注意下面的手动输入,显示如果有符号位受到影响,则结果未定义

Left shift

The left-shift operator causes the bits in shift-expression to be shifted to the left by the number of positions specified by additive-expression. The bit positions that have been vacated by the shift operation are zero-filled. A left shift is a logical shift (the bits that are shifted off the end are discarded, including the sign bit). For more information about the kinds of bitwise shifts, see Bitwise shifts.

The following example shows left-shift operations using unsigned numbers. The example shows what is happening to the bits by representing the value as a bitset. For more information, see bitset Class.

If you left-shift a signed number so that the sign bit is affected, the result is undefined. The following example shows what happens in Visual C++ when a 1 bit is left-shifted into the sign bit position.

#include <iostream>
#include <bitset>
using namespace std;

int main() {
short short1 = 16384;
bitset<16> bitset1{short2};
cout << bitset1 << endl; // 0100000000000000

short short3 = short1 << 1;
bitset<16> bitset3{short3}; // 16384 left-shifted by 1 = -32768
cout << bitset3 << endl; // 100000000000000

short short4 = short1 << 14;
bitset<16> bitset4{short4}; // 4 left-shifted by 14 = 0
cout << bitset4 << endl; // 000000000000000
}

关于c - 按位乘法和除法不适用于大数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35183899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com