c++ - 像 unsigned int 一样转换类型转换的有符号 int

标签 c++ casting

我有一个输出值的程序,将其称为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”。

energy_base 本身被定义为 double 型,但它是从一个函数生成的,(对于本例)我将其限制为“整数”值。对于上下文,total_sites 一个无符号整数。

我哪里出错了?

最佳答案

在无符号+有符号的情况下,无符号获胜。 (int) energy_base 转换为无符号整数,以便与 2*total_sites 相加。

关于c++ - 像 unsigned int 一样转换类型转换的有符号 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20393427/

相关文章:

c++ - 为什么一个表达式中的 std::string 连接给出的结果与 char by char 的结果不同?

c# - 泛型显式转换

C++ 指针转换

c++ - 带有反向迭代器的 std::vector 上的 std::lower_bound 产生错误的结果

c++ - STL 删除没有按预期工作?

c++ - 如果未使用 CloseHandle 正确关闭,则重新打开串行端口会失败

C++ 如何使用引用进行转换?

swift - 如何在 swift 中使用带有开关的 AS 来获取类类型

c++ - 将单个字节从 Enum 附加到 NSMutableData

c++ - LUID_AND_ATTRIBUTES 属性为 3