c++ - C++中不同数据类型之间的转换

标签 c++ floating-point int implicit-conversion explicit-conversion

致力于在 C++ 中的不同数据类型之间进行转换...下面的程序打印:

>"Number is 2"
>"Number is 2.5"
>"Number is 2" 

请解释为什么最后的打印输出不是“Number is 2.5”,而我希望在 C++ 样式强制转换为 float 之后?

#include <iostream>
#include <conio.h>
using namespace std;

int main() {

    int iNumber = 5;
    float fNumber;

    // No casting - C++ implicitly converts the result into an int and saves into a float
    // which is a conversion from 'int' to 'float' with possible loss of data
    fNumber = iNumber / 2;
    cout << "Number is " << fNumber << endl;

    // C-style casting not recommended as not type safe
    fNumber = (float) iNumber / 2;
    cout << "Number is " << fNumber << endl;

    // C++ style casting using datatype constructors to make the casting safe
    fNumber = static_cast<float>(iNumber / 2);
    cout << "Number is " << fNumber << endl;

   _getch();

   return 0;
}

最佳答案

声明

fNumber = static_cast<float>(iNumber / 2);

在转换为 float 之前将一个整数除以一个整数。这导致以下步骤:

  1. int iNumber 除以 int 2 --> 结果为 2
  2. 将结果转换为 float --> 得到 float 2。

如果你这样做:

fNumber = static_cast<float>(iNumber / 2.0);

现在除法的结果将是转换前的 float 类型 2.5,您应该按预期得到 2.5。

这一切都很好,但那是为什么

fNumber = (float) iNumber / 2;

工作?这是因为您在除法运算之前将 iNumber 转换为 float ,所以这里再次将 float 除以 int,结果将是 2.5 的 float 。

关于c++ - C++中不同数据类型之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39733488/

相关文章:

c++ - error C2352 非法调用非静态成员函数

c++ - glibc 上的 valgrind 输出在 C++ 中检测到错误

c++ - 寻找搬迁的起源

python - Pandas df.loc 比较浮点条件从不工作

c++ - 在 C++ 中 float 比 IEEE 754 更小的范围

c - 如何定义 float 组

python - 从字符串到整数的列表理解更改输出

java - 如何在java中添加自己的数字范围

c++ - c++ 中的接口(interface)类与类型

JAVA:[-255...255] int 到 2 字节数组