Answer the question
In order to leave comments, you need to log in
How to deal with division and types in C?
For example, in the course of some calculations, I got 2 numbers. The first is the accumulated amount. The second number of numbers. For example, you need to find the arithmetic mean. How to proceed in this case? The value can be both integer and real, although only integers will be involved in the calculations.
Example:
printf("%d\n", 23 / 4);
printf("%f\n", 23 / 4); // (float) 23 / 4
Answer the question
In order to leave comments, you need to log in
If you want the division to "take into account" a possible fractional part, then:
- always in division one of the numbers must be float (double)
- always place the result in float (double)
It is not known in advance what the result will be, integer or real.
In C, every constant has a type. 23 and 4 are two integer constants, the division operation is applied to them, as a result of an arithmetic operation on integers, there will always be an integer. For a constant to be floating point, it must contain a period. Those. Correctly 23./4.
- re-read about the task of constants.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question