【问题标题】:Multiplying two uint16_t numbers results in an int [duplicate]将两个 uint16_t 数字相乘得到一个 int [重复]
【发布时间】:2018-10-08 10:00:17
【问题描述】:

看看下面的sn-p:

#include <iostream>
#include <cstdint>
#include <boost/type_index.hpp>
using boost::typeindex::type_id_with_cvr;
int main(int argc, char** argv)
{
        constexpr uint16_t b = 2;
        constexpr uint16_t c = 3;
        constexpr const auto bc = b * c;
        std::cout << "b: " << type_id_with_cvr<decltype(b)>().pretty_name() << std::endl;
        std::cout << "b * c: " << type_id_with_cvr<decltype(bc)>().pretty_name()  << std::endl;
}

这会导致以下结果:

b: unsigned short const

b * c: int const

为什么将两个非单整数相乘得到一个整数?

编译器:g++ 5.4.0

【问题讨论】:

    标签: c++


    【解决方案1】:

    unsigned short 值被隐式转换为 int 乘法之前。

    shortchar 被认为是“存储类型”,并在进行计算之前隐式转换为 int。这就是原因

    unsigned char x = 255, y = 1;
    printf("%i\n", x+y); // you get 256, not 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 2015-04-19
      相关资源
      最近更新 更多