整数除法始终为零 [英] Integer division always zero
问题描述
可能重复:
C编程部门
可能我的问题很简单愚蠢。
我想存储一个部门的值,特别是 1 / x
其中 x
是一个
整数值。
probably my question is very simple and stupid.
I would like to store the value of a division, in particular 1 / x
where x
is a
integer value.
int x = 17;
double result = 1/x;
我尝试这样做,但我总是得到 0.000000 ...
我尝试输入固定在x中的值,例如
1/17
,但总是得到相同的值..什么是错误?
I try to do it but I always get 0.000000 ...
I try to enter a value fixed in x, for example 1/17
but always get the same value .. what's Wrong?
推荐答案
您正在进行整数除法。
尝试以下操作,它将按预期工作:
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
.
这篇关于整数除法始终为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!