整数除法总是为零 [英] Integer division always zero

查看:958
本文介绍了整数除法总是为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C编程部门


可能我的问题很简单,愚蠢。
我想存储一个除法的值,特别是 1 / x 其中 x 是一个
整数值。

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



我尝试这样做,但我总是得到 0.000000 ... 我尝试输入一个固定的值x,例如 1/17 ,但总是得到相同的值..什么是错误?

$ b



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



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

表达式中的 1 你有上面的 int ,并且 x 的类型是int。当你做 int / int 时,你得到一个int。您需要至少一个类型为浮点数( float double ),以便浮点除法



与数学不同,C ++中的除法可以引用截断的整数除法(你所做的)或浮点除法(我在我的例子中做的)。注意这个!



在我的例子中,我们明确的是 double / int - > double


Possible Duplicate:
C programming division

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;

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?

解决方案

You are doing integer division.

Try the following and it will work as expected:

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

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.

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!

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

这篇关于整数除法总是为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆