moa*_*ala 28 c++ floating-point integer type-conversion typecast-operator
在C++中用于将float类型的数据转换为整数的不同技术有哪些?
#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;
}
Run Code Online (Sandbox Code Playgroud)
the*_*man 49
你要找的是'铸造'.类型转换(将您想知道的类型放在括号中)告诉编译器您知道自己在做什么并且很酷.从C继承的旧方法如下.
float var_a = 9.99;
int var_b = (int)var_a;
Run Code Online (Sandbox Code Playgroud)
如果你只是想写
int var_b = var_a;
Run Code Online (Sandbox Code Playgroud)
你会得到你不能隐式(自动)转换警告float到int,因为你失去的小数.
这被称为旧的方式,因为C++提供了一个更好的选择,'静态演员'; 这提供了一种从一种类型转换为另一种类型的更安全的方式.等效的方法是(以及你应该这样做的方式)
float var_x = 9.99;
int var_y = static_cast<int>(var_x);
Run Code Online (Sandbox Code Playgroud)
这种方法可能看起来有点冗长,但它提供了更好的处理方式,例如在无法转换的类型上意外请求"静态强制转换".有关您应该使用静态强制转换的原因的详细信息,请参阅此问题.
Nav*_*een 30
正常的方法是:
float f = 3.4;
int n = static_cast<int>(f);
Run Code Online (Sandbox Code Playgroud)
zol*_*i2k 12
某些浮点类型的大小可能超过int.此示例显示了int使用该int safeFloatToInt(const FloatType &num);函数的任何float类型的安全转换:
#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;
}
Run Code Online (Sandbox Code Playgroud)
结果:
Unsafe conversion of value:2.2518e+15
2147483647
43
23333
Run Code Online (Sandbox Code Playgroud)
小智 7
对于大多数情况(浮点数 long,double 和 long double 的 long long):
long a{ std::lround(1.5f) }; //2l
long long b{ std::llround(std::floor(1.5)) }; //1ll
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
145163 次 |
| 最近记录: |