为什么给我输出 2 我使用类型转换?

Why does give me output 2 where i'm used type cast?

本文关键字:类型转换 输出 为什么      更新时间:2023-10-16

我正在尝试使用以下代码键入 cast int 以浮动。我在使用类型转换之前工作。但这行不通。请帮帮我。

int n;
n=5;
n=(float)n/2;
cout<<n<<endl;

"我预计 5/2 的输出是 2.5,但实际输出是 2。">

我希望 5/2 的输出是 2.5,但实际输出是 2 ?

为了获得2.5结果n应该float类型而不是int类型,整数不能像2.5那样容纳浮点数。

试试这个版本

int n = 5;
float res = (float)n/2;

并打印res

参数 n 是一个整数。因此,您尝试为其分配一个浮点数,但他是一个整数。您应该使用另一个类型为 float 的变量或打印它。