简体   繁体   English

BIT移位运算符不起作用

[英]BIT Shifting operator not working

The variable z has been declared as long long unsigned int so the range is 0 to 18,446,744,073,709,551,615 but the following program fails to compute the required values after some iterations. 变量z已声明为long long unsigned int,因此范围为0到18,446,744,073,709,551,615,但是以下程序在某些迭代后无法计算所需的值。

#include<stdio.h>

int main()
{
    long long unsigned int z=2;

    int i;

    for(i=0;i<40;i++)
    {
        printf("%d\n",z<<i);
    }

    return 0;
}

The problem is with your printf statement. 问题出在您的printf语句上。

Updated code 更新的代码

#include <iostream>

int main()
{
    long long unsigned int z = 2;

    int i;

    for (i = 0; i<40; i++)
    {
        std::cout << (z << i) << "\n";
    }

    return 0;
}

Output 输出量

2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
2147483648
4294967296
8589934592
17179869184
34359738368
68719476736
137438953472
274877906944
549755813888
1099511627776

尝试printf("%llu\\n",z<<i);

That's because %d is for printing int , not larger types. 这是因为%d用于打印int ,而不是更大的类型。

The following works: 以下作品:

#include <iostream>

int main()
{
    long long unsigned int z=2;

    for (int i = 0; i < 40 ; i++)
    {
       std::cout << (z<<i) << "\n";
    }
}

您应该在printf格式化字符串中使用"%lld\\n" ,而不是"%d\\n"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM