[英]How to convert a float into an unsigned int in C++?
I want to convert a float to an unsigned int.我想将浮点数转换为无符号整数。 When I use this code, the terminal print 3:
当我使用此代码时,终端打印 3:
#include <iostream>
int main() {
float test = 3.4;
std::cout << "test : " << int(test) << "\n";
}
But when I use this code I have an error:但是当我使用这段代码时,我有一个错误:
#include <iostream>
int main() {
float test = 3.4;
std::cout << "test : " << unsigned int(test) << "\n";
}
My error is:我的错误是:
example.cc: In function ‘int main()’:
example.cc:5:29: error: expected primary-expression before ‘unsigned’
5 | std::cout << "test : " << unsigned int(test) << "\n";
|
Can someone help me?有人能帮我吗? I need to use an unsigned int.
我需要使用无符号整数。 Thanks !
谢谢 !
The functional cast ( type(expr)
, that is) requires the type to be spelled as a single word (without spaces, []
, *
, &
, etc).功能转换(
type(expr)
,即)要求将类型拼写为单个单词(没有空格, []
, *
, &
等)。
unsigned int
is not a single word, so it's not allowed. unsigned int
不是一个单词,所以它是不允许的。
Your options are:您的选择是:
Using the regular C-style cast: (unsigned int)test
.使用常规的 C 风格转换:
(unsigned int)test
。
Omitting the int
.省略
int
。 unsigned
alone means the same thing as unsigned int
, so you can write unsigned(test)
.单独的
unsigned
与unsigned int
的含义相同,因此您可以编写unsigned(test)
。
Using a static_cast
: static_cast<unsigned int>(test)
.使用
static_cast
: static_cast<unsigned int>(test)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.