整数不会重复超过随机数

An integer won't double past a random number

本文关键字:随机数 整数      更新时间:2023-10-16

我最近开始学习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。我觉得数字应该绕一圈。

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

0 to +18446744073709551615

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

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

请注意,不同的计算机体系结构可能会有所不同。

int是一个有符号(通常为32位(数字,它只能容纳-2147483648到2147483647之间的数字。当您试图输入这么大的数字时,std::cin无法做到这一点,而是设置了可能的最大值。

现在,您正试图将要保持的最大值乘以2,这会导致溢出和UB,从技术上讲,任何事情都可能发生在您的代码中,但您使用的编译器似乎发生了以下情况。

int是2补码,这意味着最大值具有以下比特表示。

01111111111111111111111111111111111,或十六进制中的0x7fffffff

当你试图乘以2时,你做的是左1位,你得到了

1111111111111111111111111111111111 0或表示-2的0xfffffffe。

请记住,即使您现在使用的编译器和标志/优化发生了这种情况,使用不同的编译器和标记也会产生不同的结果,因为您会导致"未定义行为"。