Home > Software design >  Two different result values, I've been researching for days and still can't understand
Two different result values, I've been researching for days and still can't understand

Time:05-10

Below is the code:

#include <stdio.h>

int main(void) {
    float toobig = 3.4E38 * 100.0f;
    float toosmall = (0.1234E-10) / 10;
    printf("%f\n", toobig);
    printf("%e\n", toosmall);
    return 0;
}

The result of running after compilation is:

PS D:\c\test1> .\a
1.#INF00
1.234000e-012

But the value of toosmall on the book is:

0.0123E-10

I have been researching this problem for a few days, but I still can't understand the result of the compiler running: 1.234000e-012, why is it different from the book?

CodePudding user response:

The program behaves almost as expected according to the C Standard:

toolarge is indeed beyond the range of the float type on your system. Note that the expression 3.4E38 * 100.0f is evaluated using double arithmetics because 3.4E38 is a double constant.

The value of toosmall is a the closest approximation of 0.01234E-10 that fits in a float, converting it with %e produces a decimal representation with one non-zero digit before the ., 6 decimals and an exponent that should be at least 2 digits and at most as many are needed to represent the exponent, using a small case e. The expected output is 1.234000e-12.

The book's 0.0123E-10 is completely incorrect, not even using the right exponent indicator. There are probably many more errors in this book.

Your C library is incorrect too because there should be just 2 digits in the exponent. Judging from the shell prompt, you probably use Turbo-C, which is a very old compiler that does not conform to the C Standard.

CodePudding user response:

It looks like your "book" is acting weird. See there.

What you see on your machine is the correct behaviour.

By the way I don't understand the name of the variable toosmall. in usual 3é bits float representation you can go down to e-38 approcimatively

  •  Tags:  
  • c
  • Related