For example, in a standard stream enter a number (floating point) + number (floating point) and output the result (floating point number) without using float, double
- 2for example, using fixed-point numbers - MBo
1 answer
The operations of addition and subtraction are trivially transferred to the conceptual representation with a fixed point . That is, 123.456 can be represented as an integer 123456 , and the number 789.123 , as the number 789123 . The sum of these numbers, with the correct point (three digits to the right), will give you the correct answer to the question about the sum of the original numbers 123.456 and 789.123 . In other words, all floating numbers in this approach are converted to integers through multiplication by some fixed factor M ( 1000 in my example) and the subsequent rounding. In this case, the correctness of the operations of addition and subtraction is preserved in a trivial way.
The multiplication operation for such numbers is also implemented rather trivially β one must perform integer multiplication and simply divide its result by the factor M The division operation is implemented by pre-multiplying the divisor by M and then performing integer division.
Sketchy (Attention: Reading numbers through scanf will not work correctly on some inputs. To correctly read the fractional part, you will need some more complex code.)
#include <stdio.h> #define M 1000 int main(void) { unsigned long long a, b, c, w, f; // Π§ΠΈΡΠ°Π΅ΠΌ `a` scanf("%llu.%3llu%*[0-9]", &w, &f); while (f >= M) f /= 10; a = w * M + f; // Π§ΠΈΡΠ°Π΅ΠΌ `b` scanf("%llu.%3llu%*[0-9]", &w, &f); while (f >= M) f /= 10; b = w * M + f; // Π‘Π»ΠΎΠΆΠ΅Π½ΠΈΠ΅ - ΡΡΠΎ ΠΎΠ±ΡΡΠ½ΠΎΠ΅ ΡΠ»ΠΎΠΆΠ΅Π½ΠΈΠ΅ c = a + b; // ΠΡΠ²ΠΎΠ΄ΠΈΠΌ ΡΠ΅Π·ΡΠ»ΡΡΠ°Ρ printf("%llu.%03llu + %llu.%03llu = %llu.%03llu\n", a / M, a % M, b / M, b % M, c / M, c % M); // Π£ΠΌΠ½ΠΎΠΆΠ΅Π½ΠΈΠ΅ - ΡΡΠΎ ΠΎΠ±ΡΡΠ½ΠΎΠ΅ ΡΠΌΠ½ΠΎΠΆΠ΅Π½ΠΈΠ΅ Ρ ΠΏΠΎΡΡ-ΠΊΠΎΡΡΠ΅ΠΊΡΠΈΠ΅ΠΉ c = a * b / M; // ΠΡΠ²ΠΎΠ΄ΠΈΠΌ ΡΠ΅Π·ΡΠ»ΡΡΠ°Ρ printf("%llu.%03llu * %llu.%03llu = %llu.%03llu\n", a / M, a % M, b / M, b % M, c / M, c % M); } - oneUnchanged was more understandable)) - user310127
- To perform this operation (calculations) arrays need to use? - user310127
- @ King.c: Um ... No, there is no obvious need for arrays. - AnT
- And how to implement it?) Does not work - user310127
- 3Do you have some kind of prog or something similar to clearly understand the essence of the task - user310127