我有一个输出值的程序,调用它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 是无符号整数.
我哪里错了?
在unsigned + signed,unsigned wins中.(int) energy_base
转换为unsigned int以进行添加2*total_sites
.