C++ 浮点到整数类型的转换

C++ floating point to integer type conversions(C++ 浮点到整数类型的转换)
本文介绍了C++ 浮点到整数类型的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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++ 浮点到整数类型的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)