Arithmetic Operations

  • Thread starter Thread starter Xarky
  • Start date Start date
X

Xarky

Hi,
I am trying to work out the following equation

double x;
x = 2/40;

The value of x being reported is 0;
The real answer should be 0.05.

Can someone explain me why this occurs and how I can solve it.


Thanks in Advance
 
You should specify explicitly that those numbers are System.Double.
For instance:
double x;
x = 2D / 40D;
 
Xarky said:
Hi,
I am trying to work out the following equation

double x;
x = 2/40;

The value of x being reported is 0;
The real answer should be 0.05.

Can someone explain me why this occurs and how I can solve it.

2 and 40 are integers so the result of 2/40 is an integer. If you cast
as double that would work. Ex:

x = (double)2/40;

Or use the suffix for double. Ex:

x = 2/40d;
 
Xarky said:
Hi,
I am trying to work out the following equation

double x;
x = 2/40;

The value of x being reported is 0;
The real answer should be 0.05.

Can someone explain me why this occurs and how I can solve it.

2 and 40 are both integers, so it is doing integer division (this effectively truncates any decimal points). In order to get the
decimal, at least one of the values must not be an integral type (make one either float or double). This could be done by simply
changing it to:
x = 2.0/40;
or
x = 2/40.0;
 
Back
Top