如何在 C++ 中将 float 转换为 unsigned int?

How to convert a float into an unsigned int in C++?

我想将 float 转换为 unsigned int。当我使用这段代码时,终端打印 3 :

#include <iostream>

int main() {
  float test = 3.4;
  std::cout << "test : " << int(test) << "\n";
}

但是当我使用这段代码时出现错误:

#include <iostream>

int main() {
  float test = 3.4;
  std::cout << "test : " << unsigned int(test) << "\n";
}

我的错误是:

example.cc: In function ‘int main()’:
example.cc:5:29: error: expected primary-expression before ‘unsigned’
    5 |   std::cout << "test : " << unsigned int(test) << "\n";
      |    

有人可以帮助我吗?我需要使用一个无符号整数。 谢谢!

功能转换type(expr),即)要求类型拼写为单个单词(不带空格,[]*, &, 等等).

unsigned int不是一个单词,所以不允许。

您的选择是:

  • 使用常规 C 风格转换:(unsigned int)test.

  • 省略intunsigned单独和unsigned int是一样的意思,所以可以写成unsigned(test).

  • 使用 static_cast: static_cast<unsigned int>(test).