为什么它不返回 c++ 中除数的浮点值

Why it not return the float value of the divison in c++?

本文关键字:返回 c++ 为什么      更新时间:2023-10-16

我在 c++ 中有这段代码:

#include <iostream>
using namespace std;
int main() {
 float division = 5/2;
 cout<<division;
 return 0;
}

但是它返回2,而不是2.5,为什么?

因为你是在划分int egers,而不是float s。将结果分配给什么与除法的执行方式无关。

如果要划分浮点数,请执行

float division = 5.f/2.f;