且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

整数除法始终为零

更新时间:2022-12-14 15:14:41

您正在进行整数除法。

尝试以下操作,它将按预期工作:

Try the following and it will work as expected:

int x = 17;
double result = 1.0 / x;

表达式中 1 的类型你以上是 int ,而 x 的类型是int。当你执行 int / int ,你会得到一个int回来。您需要至少有一种涉及浮点的类型( float double ),以便浮点除法发生。

The type of the 1 in the expression you have above is int, and the type of x is int. When you do int / int, you get an int back. You need at least one of the types involved to be floating point (float or double) in order for floating point division to occur.

与数学不同,C ++中的划分可以指截断的整数除法(你所做的)还是浮点除法(在我的例子中我做了什么)。小心这个!

Unlike in Mathematics, division in C++ can either refer to truncated integer division (what you did) or floating point division (what I did in my example). Be careful of this!

在我的例子中,我们明确地说明了 double / int - >双重

In my example, explicitly what we have is double / int -> double.