c++ - 整数不会超过随机数

标签 c++

最近开始学习C++,做了这个小程序

#include <iostream> // for std::cout << / std::cin >> / std::endl; / '\n'
#include <cstdlib>  // for EXIT_SUCCESS and EXIT_FAILURE


int input()
{
    int imp_num{ 0 };
    std::cin >> imp_num;
    return imp_num;
}
void output(int result)
{
    std::cout << "The dubble of that number is : " << result  << '\n';
}
int main() 
{
    std::cout << "Enter a number: ";
    int inp_num{ input() };      // asks the user to enter a number and saves it 
    int result{ inp_num * 2 };   // calculates the result 
    output(result);              // outputs the result


    system("pause");             //prevents the console from terminating
    return 0;
}

当恢复的数字为 10 位或更多时,就会出现问题。那时程序只是一个随机数(通常是 -2),无论我输入什么,它都将始终保持不变,并且只有在我重新编译源代码时才会发生变化。

Enter a number: 23213231231231212312
The dubble of that number is : -2
Press any key to continue . . .
Enter a number: 12311111111111111111111111
The dubble of that number is : -2
Press any key to continue . . .

我重新编译源码

Enter a number: 1231212123133333333333321
The dubble of that number is : 3259
Press any key to continue . . .

将所有 int 更改为 int64_t 并不能解决问题,但奇怪的是,此处出现了 -2 的相同输出。

Enter a number: 1231212123133333333333321
The dubble of that number is : -2
Press any key to continue . . .

我不明白为什么在发生整数溢出时会出现所有数字 -2。我认为数字应该绕一圈。

最佳答案

您给出的值 1231212123133333333333321 远远大于 uint64_t 可以容纳的值(溢出)。在我的例子中,uint64_t(占用 8 字节数据)数据类型的最大范围是:

0 to +18446744073709551615

要了解您平台的限制,即实际上,请借助 C++ 库 limits:

#include <limits>
std::cout << std::numeric_limits<uint64_t>::max() << std::endl;

请注意,它可能因不同的计算机架构而异。

关于c++ - 整数不会超过随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62908579/

相关文章:

C++ 错误、类和构造函数

c++ - 在重载选择期间不考虑默认参数的转换?

c++ - "dual inheritance"指针

c++ - 即时编译 C++ : clang/libtooling fails to set Triple for LLVM IR

c++ - 使用c++程序在shell中更改目录

c++ - 类中的 ifstream 变量

c++ - C/C++ - 可执行路径

c++ - 在不删除的情况下将字符串拆分为具有多个分隔符的多个字符串?

c++ - 从哪里获得简单的开源 adpcm C\C++ 编码器库?

C++ 聚合初始化与 C 风格的数组