Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer division always zero [duplicate]

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?

like image 620
Safari Avatar asked Feb 26 '12 17:02

Safari


People also ask

Can a division result in zero?

Non-standard analysis. In the hyperreal numbers and the surreal numbers, division by zero is still impossible, but division by non-zero infinitesimals is possible.

Is division of any integer by zero define?

The division of any integer by zero is meaningless.

Why do I get 0 when I divide in Python?

In mathematics, division by 0 is undefined. Because of this, Python will issue the above error when your code tries to accomplish this undefined expression.

Why is double divided by infinity zero?

In case of double/float division, the output is Infinity, the basic reason behind that it implements the floating point arithmetic algorithm which specifies a special values like “Not a number” OR “infinity” for “divided by zero cases” as per IEEE 754 standards.


1 Answers

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.

like image 145
Mike Bailey Avatar answered Oct 19 '22 23:10

Mike Bailey