Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get fractions in an integer division?

Tags:

How do you divide two integers and get a double or float answer in C?

like image 484
Chad Carisch Avatar asked Jun 04 '10 16:06

Chad Carisch


People also ask

How do you divide fractions with an integer?

To divide fractions by a whole number, we divide the numerator by the whole number and the denominator stays the same.

How do you do fractions in division?

The first step to dividing fractions is to find the reciprocal (reverse the numerator and denominator) of the second fraction. Next, multiply the two numerators. Then, multiply the two denominators. Finally, simplify the fractions if needed.

Is there a fraction in integers?

Key idea: Like whole numbers, integers don't include fractions or decimals.

What is an example of integer division?

Division of integers means equal grouping or dividing an integer into a specific number of groups. For example, -6 ÷ 2 means dividing -6 into 2 equal parts, which results in -3.


2 Answers

You need to cast one or the other to a float or double.

int x = 1; int y = 3;  // Before x / y; // (0!)  // After ((double)x) / y; // (0.33333...) x / ((double)y); // (0.33333...) 

Of course, make sure that you are store the result of the division in a double or float! It doesn't do you any good if you store the result in another int.


Regarding @Chad's comment ("[tailsPerField setIntValue:tailsPer]"):

Don't pass a double or float to setIntValue when you have setDoubleValue, etc. available. That's probably the same issue as I mentioned in the comment, where you aren't using an explicit cast, and you're getting an invalid value because a double is being read as an int.

For example, on my system, the file:

#include <stdio.h> int main() {     double x = 3.14;     printf("%d", x);     return 0; } 

outputs:

1374389535

because the double was attempted to be read as an int.

like image 164
Mark Rushakoff Avatar answered Sep 23 '22 06:09

Mark Rushakoff


Use type-casting. For example,

main()     {         float a;         int b = 2, c = 3;         a = (float) b / (float) c;     // This is type-casting         printf("%f", a);     } 
like image 40
Pranav Totla Avatar answered Sep 21 '22 06:09

Pranav Totla