似乎MSVC编译器不同地处理有符号和无符号溢出。当转换超过最大整数值的double值时,结果是可能的最小整数值(始终相同)。当转换为unsigned int时,转换会按预期产生溢出(最大unsigned int值+ 1产生0,最大unsigned int + 2产生1,......) 有人可以解释编译器的行为,还是一个bug?
经过测试的编译器MSVC 10和14
#define BOOST_TEST_MODULE Tests
#include <boost/test/unit_test.hpp>
#include <climits>
#include <iostream>
BOOST_AUTO_TEST_CASE(test_overflow_signed) {
double d_int_max_1 = INT_MAX + 1.; //2147483647 + 1
double d_int_max_2 = INT_MAX + 2.; //2147483647 + 2
BOOST_CHECK((int)(2147483648.) != (int)(2147483649.)); //succeeds (overflows to -2147483648 and -2147483647)
BOOST_CHECK((int)(d_int_max_1) != (int)(d_int_max_2)); //fails (both values overflow to -2147483648)
std::cout << "(int)(2147483648.) == " << (int)(2147483648.) << std::endl; //-2147483648
std::cout << "(int)(2147483649.) == " << (int)(2147483649.) << std::endl; //-2147483647
std::cout << "(int)(d_int_max_1) == " << (int)(d_int_max_1) << std::endl; //-2147483648
std::cout << "(int)(d_int_max_2) == " << (int)(d_int_max_2) << std::endl; //-2147483648
}
BOOST_AUTO_TEST_CASE(test_overflow_unsigned) {
double d_int_max_1 = UINT_MAX + 1.;//4294967295 + 1
double d_int_max_2 = UINT_MAX + 2.;//4294967295 + 2
//BOOST_CHECK((unsigned int)(4294967296.) != (unsigned int)(4294967297.)); //compiler fails (!= truncation of constant value)
BOOST_CHECK((unsigned int)(d_int_max_1) != (unsigned int)(d_int_max_2)); //succeeds (overflows to 0 and 1)
std::cout << "(unsigned int)(d_int_max_1) == " << (unsigned int)(d_int_max_1) << std::endl; //0
std::cout << "(unsigned int)(d_int_max_2) == " << (unsigned int)(d_int_max_2) << std::endl; //1
}
答案 0 :(得分:0)
[conv.fpint] / 1 浮点类型的prvalue可以转换为整数类型的prvalue。转换截断;也就是说,丢弃小数部分。 如果截断值不可以,则行为未定义 以目的地类型表示。
强调我的。由于行为未定义,任何结果都是正确的。