D
D
dandropov952018-09-22 09:14:26
C++ / C#
dandropov95, 2018-09-22 09:14:26

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

In the first case, all the norms turn out that in fact there is no arithmetic mean, since the fractional part is discarded.
In the second case, since only integers are involved in the calculation, the result is zero when output as a real number.
What is the correct way to write this? It is not known in advance what the result will be, integer or real.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GavriKos, 2018-09-22
@GavriKos

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)

R
res2001, 2018-09-22
@res2001

It is not known in advance what the result will be, integer or real.

If there are chances that the result of the calculation may not be an integer (and you really need a real result in this case, i.e. with a remainder), then you need to use real operations to evaluate the expression, not integers.
It is often necessary to discard the remainder, in which case integer arithmetic is deliberately used.
Unlike languages ​​with dynamic typing, in C / C ++ the programmer himself must control the type of the result of the expression and where it is necessary to do type conversions explicitly to obtain the result of the desired type.
And this is not a lack of language.

V
Vladimir Dubrovin, 2018-09-22
@z3apa3a

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 question

Ask a Question

731 491 924 answers to any question