我有一个输出值的程序,将其称为x
,它可以是任何数字类型。当我将 x
类型转换为 (int)x
时,对于正数,它工作正常,但对于负数,它似乎被视为无符号。 (对 INT_MAX +1 进行模运算)。
我将它用作数组索引,突然间我收到了许多“out_of_range”错误,因此我插入了一些 printfs 并将 x 设为整数,然后将其作为我的输出:
Before: 44 After: 44
Before: -60 After: 4294967236
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Aborted (core dumped)
使用命令:
std::cout << "Before: " << 2*total_sites + energy_base << "\tAfter: " << 2*total_sites + (int)energy_base << std::endl;
其中 energy_base
是我在示例中使用的“x”。
我哪里出错了?
最佳答案
在无符号+有符号的情况下,无符号获胜。 (int) energy_base
转换为无符号整数,以便与 2*total_sites
相加。
关于c++ - 像 unsigned int 一样转换类型转换的有符号 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20393427/