1

Today i come with a problem and not able to figure out what is the issue with this simple statement

I Tried

double d =1/4;

expected ans for me is 0.25 but in reality ans is 0.0 why so ??

And what should we do if statement is in terms of integer variables like this

double a =(a-b)/(d+e); 
Hot Cool Stud
  • 1,145
  • 6
  • 25
  • 50

4 Answers4

7

Because what you done is here integer division. 1 / 4 always give you 0 as a result regardless which type you assing it.

.NET has 3 type of division. From 7.7.2 Division operator

  • Integer division
  • Floating-point division
  • Decimal division

From Integer division part;

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands.

If you want to 0.25 as a result, you should define one of your values as a floating point.

You can use one of these;

double d = 1d / 4d;
double d = 1d / 4;
double d = 1 / 4d;

And what should we do if statement is in terms of integer variables like this

double a =(a-b)/(d+e);

I assume your a, b, d and e are integers, you should use one of these then;

double a = (double)(a-b) / (double)(d+e);
double a = (a-b) / (double)(d+e);
double a = (double)(a-b) / (d+e);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
2
double d =1d/4; 

should work. If you don't specify the type of your numbers, it is treated as Integer. And integer 1/4 will be zero.

MichaC
  • 13,104
  • 2
  • 44
  • 56
1

/ Operator (msdn)

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%). To obtain a quotient as a rational number or fraction, give the dividend or divisor type float or type double. You can assign the type implicitly if you express the dividend or divisor as a decimal by putting a digit to the right side of the decimal point.

Try this:

double d = 1.0 / 4.0;
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
1

Use this:

double d = (double) 1 / 4;
Iswanto San
  • 18,263
  • 13
  • 58
  • 79