为什么我的变量在应用移位运算符后没有改变?

发布于 2024-11-15 10:44:56 字数 138 浏览 2 评论 0原文

int main()
{
    int i=3;
    (i << 1);
    cout << i; //Prints 3
}

由于左移一位,我预计会得到 6。为什么它不起作用?

int main()
{
    int i=3;
    (i << 1);
    cout << i; //Prints 3
}

I expected to get 6 because of shifting left one bit. Why does it not work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

巷雨优美回忆 2024-11-22 10:44:56

因为移位运算符返回一个值。

您想要这样:

#include <iostream>

int main()
{
     int i = 3;
     i = i << 1;
     std::cout << i;
}

移位运算符不会“就地”移位。您可能正在考虑其他版本。如果他们这样做,就像许多其他 C++ 二元运算符一样,那么我们就会发生非常糟糕的事情。

i <<= 1; 

int a = 3;
int b = 2;
a + b;    // value thrown away
a << b;   // same as above

Because the bit shift operators return a value.

You want this:

#include <iostream>

int main()
{
     int i = 3;
     i = i << 1;
     std::cout << i;
}

The shift operators don't shift "in place". You might be thinking of the other version. If they did, like a lot of other C++ binary operators, then we'd have very bad things happen.

i <<= 1; 

int a = 3;
int b = 2;
a + b;    // value thrown away
a << b;   // same as above
〗斷ホ乔殘χμё〖 2024-11-22 10:44:56

您应该使用 <<= 否则该值就会丢失。

You should use <<= or the value is just lost.

何以笙箫默 2024-11-22 10:44:56

您没有将表达式 (i << 1); 的值分配回 i

尝试:

i = i << 1;

或者(相同):

i <<= 1;

You're not assigning the value of the expression (i << 1); back to i.

Try:

i = i << 1;

Or (same):

i <<= 1;
林空鹿饮溪 2024-11-22 10:44:56

您需要将 i 分配给移位后的值。

int main()
{
    int i=3;
    i <<= 1;
    cout << i; //Prints 3
}

或者,您可以使用 <<= 作为赋值运算符:

i <<= 1;

You need to assign i to the shifted value.

int main()
{
    int i=3;
    i <<= 1;
    cout << i; //Prints 3
}

Alternatively, you can use <<= as an assignment operator:

i <<= 1;
孤城病女 2024-11-22 10:44:56

因为你没有把答案分配给i。

i = i << 1;

Because you didn't assign the answer back to i.

i = i << 1;
帅气尐潴 2024-11-22 10:44:56

您需要使用 i<<=1 将值重新分配回 i (使用“左移和赋值运算符”)

You need to reassign the value back to i with i<<=1 (using "left shift and assign operator")

清眉祭 2024-11-22 10:44:56

原因:
我<< 1 产生一个中间值,该中间值不会保存回变量i

// i is initially in memory
int i=3;

// load i into register and perform shift operation,
// but the value in memory is NOT changed
(i << 1);

// 1. load i into register and perform shift operation
// 2. write back to memory so now i has the new value
i = i << 1;

为了您的意图,您可以使用:

// equal to i = i << 1
i <<= 1;

Reason:
i << 1 produce an intermediate value which is not saved back to variable i.

// i is initially in memory
int i=3;

// load i into register and perform shift operation,
// but the value in memory is NOT changed
(i << 1);

// 1. load i into register and perform shift operation
// 2. write back to memory so now i has the new value
i = i << 1;

For your intention, you can use:

// equal to i = i << 1
i <<= 1;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文