简体   繁体   English

类型转换带符号的int转换方式类似于无符号的int

[英]Typecasted signed int converting like unsigned int

I have a program which outputs a value, call it x which could be of any numerical type. 我有一个输出值的程序,称它为x ,它可以是任何数字类型。 When I typecast x as (int)x , for positive numbers it works fine, but for negative numbers it seems to be treated it as unsigned. 当我将x强制转换为(int)x ,对于正数它可以正常工作,但是对于负数,它似乎被视为无符号。 (Doing a modulo INT_MAX +1). (对INT_MAX +1做模)。

I use it as an array index, and suddenly I was getting many "out_of_range" errors, so I inserted some printfs and made x an integer, and I got this as my output: 我将其用作数组索引,突然我收到许多“ 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)

with the command: 使用命令:

std::cout << "Before: " << 2*total_sites + energy_base << "\tAfter: " << 2*total_sites + (int)energy_base << std::endl;

where energy_base is the "x" I used in my example. 其中energy_base是我在示例中使用的“ x”。

energy_base itself is defined as a double, but it is generated from a function which (for this example), I have restricted to "integer" values. energy_base本身被定义为double,但是它是从一个函数生成的(对于本示例而言),我将其限制为“整数”值。 For context, total_sites is an unsigned integer. 对于上下文,total_sites 一个无符号整数。

Where am I going wrong? 我要去哪里错了?

In unsigned + signed, unsigned wins. 在无符号+有符号的情况下,无符号获胜。 (int) energy_base is converted to an unsigned int for the addition with 2*total_sites . (int) energy_base转换为unsigned int,用于使用2*total_sites进行加法2*total_sites

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM