C++ 浮点到整数类型转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2544394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ floating point to integer type conversions
提问by moala
What are the different techniques used to convert float type of data to integer in C++?
在 C++ 中用于将浮点型数据转换为整数的不同技术有哪些?
#include <iostream>
using namespace std;
struct database {
int id, age;
float salary;
};
int main() {
struct database employee;
employee.id = 1;
employee.age = 23;
employee.salary = 45678.90;
/*
How can i print this value as an integer
(with out changing the salary data type in the declaration part) ?
*/
cout << endl << employee.id << endl << employee.
age << endl << employee.salary << endl;
return 0;
}
回答by thecoshman
What you are looking for is 'type casting'. typecasting (putting the type you knowyou want in brackets) tells the compiler you know what you are doing and are cool with it. The old way that is inherited from C is as follows.
您正在寻找的是“类型转换”。类型转换(将你知道的类型放在括号中)告诉编译器你知道你在做什么并且很酷。从 C 继承的旧方式如下。
float var_a = 9.99;
int var_b = (int)var_a;
If you had only tried to write
如果你只是试着写
int var_b = var_a;
You would have got a warning that you can't implicitly (automatically) convert a float
to an int
, as you lose the decimal.
你会已经得到警告,你不能隐式(自动)转换float
到int
,因为你失去的小数。
This is referred to as the old way as C++ offers a superior alternative, 'static cast'; this provides a much safer way of converting from one type to another. The equivalent method would be (and the way you should do it)
这被称为旧方法,因为 C++ 提供了一种更好的替代方法,“静态转换”;这提供了一种从一种类型转换为另一种类型的更安全的方式。等效的方法是(以及你应该这样做的方式)
float var_x = 9.99;
int var_y = static_cast<int>(var_x);
This method may look a bit more long winded, but it provides much better handling for situations such as accidentally requesting a 'static cast' on a type that cannot be converted. For more information on the why you should be using static cast, see this question.
这种方法可能看起来有点冗长,但它提供了更好的处理方式,例如意外请求对无法转换的类型进行“静态转换”。有关为什么应该使用静态强制转换的更多信息,请参阅此问题。
回答by Naveen
Normal way is to:
正常方法是:
float f = 3.4;
int n = static_cast<int>(f);
回答by zoli2k
Size of some float types may exceed the size of int
.
This example shows a safe conversion of any float type to int
using the int safeFloatToInt(const FloatType &num);
function:
某些浮点类型的大小可能会超过int
. 此示例显示了从任何浮点类型到int
使用该int safeFloatToInt(const FloatType &num);
函数的安全转换:
#include <iostream>
#include <limits>
using namespace std;
template <class FloatType>
int safeFloatToInt(const FloatType &num) {
//check if float fits into integer
if ( numeric_limits<int>::digits < numeric_limits<FloatType>::digits) {
// check if float is smaller than max int
if( (num < static_cast<FloatType>( numeric_limits<int>::max())) &&
(num > static_cast<FloatType>( numeric_limits<int>::min())) ) {
return static_cast<int>(num); //safe to cast
} else {
cerr << "Unsafe conversion of value:" << num << endl;
//NaN is not defined for int return the largest int value
return numeric_limits<int>::max();
}
} else {
//It is safe to cast
return static_cast<int>(num);
}
}
int main(){
double a=2251799813685240.0;
float b=43.0;
double c=23333.0;
//unsafe cast
cout << safeFloatToInt(a) << endl;
cout << safeFloatToInt(b) << endl;
cout << safeFloatToInt(c) << endl;
return 0;
}
Result:
结果:
Unsafe conversion of value:2.2518e+15
2147483647
43
23333
回答by Roman Gorislavski
For most cases (long for floats, long long for double and long double):
对于大多数情况(浮点数 long,double 和 long double 的 long long):
long a{ std::lround(1.5f) }; //2l
long long b{ std::llround(std::floor(1.5)) }; //1ll
回答by simong
Check out the boost NumericConversionlibrary. It will allow to explicitly control how you want to deal with issues like overflow handling and truncation.
查看 boost NumericConversion库。它将允许明确控制您希望如何处理溢出处理和截断等问题。
回答by asdacap
One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.
我想补充一件事。有时,可能会出现精度损失。您可能希望在转换之前先添加一些 epsilon 值。不知道为什么会这样......但它有效。
int someint = (somedouble+epsilon);
回答by Seidr
I believe you can do this using a cast:
我相信您可以使用演员表来做到这一点:
float f_val = 3.6f;
int i_val = (int) f_val;
回答by sanjuro
the easiest technique is to just assign float to int, for example:
最简单的技术是将 float 分配给 int,例如:
int i;
float f;
f = 34.0098;
i = f;
this will truncate everything behind floating point or you can round your float number before.
这将截断浮点后面的所有内容,或者您可以之前舍入浮点数。