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

  • 2
    for example, using fixed-point numbers - MBo

1 answer 1

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); } 

http://coliru.stacked-crooked.com/a/acbf006dde1e16b6

  • one
    Unchanged 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
  • 3
    Do you have some kind of prog or something similar to clearly understand the essence of the task - user310127