Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in C# to get exact value [duplicate]

If I divide 150 by 100, I should get 1.5. But I am getting 1.0 when I divided like I did below:

double result = 150 / 100;

Can anyone tell me how to get 1.5?

like image 895
Irannabi Avatar asked Mar 14 '13 03:03

Irannabi


People also ask

How do you write division in C?

printf("Enter dividend: "); scanf("%d", &dividend); printf("Enter divisor: "); scanf("%d", &divisor); Then the quotient is evaluated using / (the division operator), and stored in quotient . quotient = dividend / divisor; Similarly, the remainder is evaluated using % (the modulo operator) and stored in remainder .

What is division function in C?

In the C Programming Language, the div function divides numerator by denominator. Based on that division calculation, the div function returns a structure containing two members - quotient and remainder.

What is float division in C?

The variables b, c, d are of float type. But the / operator sees two integers it has to divide and hence returns an integer in the result which gets implicitly converted to a float by the addition of a decimal point. If you want float divisions, try making the two operands to the / floats.


2 Answers

try:

 double result = (double)150/100;

When you are performing the division as before:

double result = 150/100;

The devision is first done as an Int and then it gets cast as a double hence you get 1.0, you need to have a double in the equation for it to divide as a double.

like image 72
Heinrich Avatar answered Sep 30 '22 05:09

Heinrich


Cast one of the ints to a floating point type. You should look into the difference between decimal and double and decide which you want, but to use double:

double result = (double)150 / 100;
like image 36
MattW Avatar answered Sep 30 '22 04:09

MattW