在输入无符号short范围之外的整数后打印无符号short值的规则是什么?

问题描述 投票:1回答:1
#include <iostream>
#include <climits>
int main(void) {
    std::cout << SHRT_MIN << std::endl;
    std::cout << SHRT_MAX << std::endl;
    //-32768 ~ 32767 is the range
    short a;
    std::cin >> a;
    std::cout << "decimal: " << a << std::endl;//decimal
    return 0;
}

请看上面的代码,观察当我输入一个超出short范围的整数时会发生什么。

当我输入小于-32768的任何整数时,如-3333333,-32768将被打印。

当我输入大于32767的任何整数时,例如3333333,将打印32767。

现在,我想查看输入无符号短裤范围之外的整数会发生什么。

这里是代码:

#include <iostream>
#include <climits>
int main(void) {
    std::cout << USHRT_MAX << std::endl;
    unsigned short a;
    std::cin >> a;
    std::cout << "decimal: " << a << std::endl;//decimal
    return 0;
}

似乎没有USHRT_MIN,但我认为它是最小的0。

因此,无符号short的范围是0〜65535的范围。

当我输入大于65535的任何整数时,如3333333,将打印65535。

现在出现了让我非常困惑的部分。

当我输入小于0的整数时,>>

-1, decimal: 65535
-2, decimal: 65534
-3, decimal: 65533
-4, decimal: 65532
...
-65534, decimal: 2
-65535, decimal: 1
-65536, decimal: 65535
-65537, decimal: 65535
-65538, decimal: 65535
-65539, decimal: 65535
-3333333, decimal: 65535

从-1到-65535,a的打印值似乎具有模式。

从-65536到任何较小的负整数,始终保持65535的打印值。

输入短整数范围之外的整数似乎是很容易遵循的规则。

对于像我这样的初学者来说,现在很难输入超出无符号短整数范围的整数。

在输入无符号short范围之外的整数后打印无符号short值的规则是什么?

#include #include int main(void){std :: cout << SHRT_MIN << std :: endl; std :: cout << SHRT_MAX << std :: endl; //-32768〜32767是...

c++ integer range short
1个回答
0
投票

仅添加检查以了解>>是否表示问题:

#include <iostream>
#include <climits>

int main(void) {
    std::cout << USHRT_MAX << std::endl;
    unsigned short a;
    if (!(std::cin >> a))
      std::cout << "wrong ";
    std::cout << "decimal: " << a << std::endl;//decimal
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.