问题描述
在 C++ 中将浮点类型的数据转换为整数有哪些不同的技术?
What are the different techniques used to convert float type of data to integer in 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;
}
推荐答案
您正在寻找的是类型转换".类型转换(将你想要的类型知道放在括号中)告诉编译器你知道你在做什么并且很酷.从C继承的旧方式如下.
What you are looking for is 'type casting'. typecasting (putting the type you know you 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.
float var_a = 9.99;
int var_b = (int)var_a;
如果你只是尝试写作
int var_b = var_a;
您会收到一条警告,提示您不能将 float
隐式(自动)转换为 int
,因为您会丢失小数点.
You would have got a warning that you can't implicitly (automatically) convert a float
to an int
, as you lose the decimal.
这被称为旧方法,因为 C++ 提供了一种更好的替代方法,即静态转换";这提供了一种从一种类型转换为另一种类型的更安全的方法.等效的方法是(以及你应该这样做的方式)
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)
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.
这篇关于C++ 浮点到整数类型的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!