对C ++ 14

时间:2018-11-10 10:10:52

标签: c++ c++14 integer-overflow unsigned-integer

为什么在uint8_t的情况下following code失败?

#include <iostream>
#include <cstdint>
#include <stack>

template <typename TT>
void PrintNumberScientificNotation (TT number) {
  constexpr TT             kBase{10};          // Base of the numerical system.
            TT             xx{number};         // Number to convert.
            TT             exponent{};         // Exponent.
            std::stack<TT> fractional_part{};  // Values in the fractional part.

  do {
    fractional_part.push(xx%kBase);
    xx /= kBase;
    exponent++;
  } while (xx > kBase);

  std::cout << xx << '.';
  while (!fractional_part.empty()) {
    std::cout << fractional_part.top();
    fractional_part.pop();
  }
  std::cout << " x 10^" << exponent << std::endl;
}

int main () {
  uint8_t number_1{255};
  PrintNumberScientificNotation(number_1);  // Does not work.
  uint16_t number_2{255};
  PrintNumberScientificNotation(number_2);  // Works.
  uint16_t number_3{65'535};
  PrintNumberScientificNotation(number_3);  // Works.
  uint32_t number_4{4'294'967'295};
  PrintNumberScientificNotation(number_4);  // Works.
  uint64_t number_5{18'446'744'073'709'551'615};
  PrintNumberScientificNotation(number_5);  // Works.
}

执行:http://cpp.sh/8c72o

输出:

. x 10^
2.55 x 10^2
6.5535 x 10^4
4.294967295 x 10^9
1.8446744073709551615 x 10^19

据我了解,uint8_t可以表示无符号整数,最大为255(包括255)(UINT8_MAX)。为什么我可以代表所有其他表示形式的最大值?

2 个答案:

答案 0 :(得分:4)

您的代码的数学部分很好,打印损坏了。

如果您将cout用于uint_t,它将把uint_t解释为字符代码。这是因为uint_t是无符号字符的类型别名。

可能的解决方法是将其显式转换为整数:

  std::cout << unsigned(xx) << '.';
  while (!fractional_part.empty()) {
    std::cout << unsigned(fractional_part.top());
    fractional_part.pop();
  }
  std::cout << " x 10^" << unsigned(exponent) << std::endl;

答案 1 :(得分:3)

uint8_t被视为一个字符,因此它将打印带有ASCII码的字符。在打印之前,必须将uint8_t值转换为unsigned,如下所示:

uint8_t number_1{255};
PrintNumberScientificNotation(unsigned(number_1));