0

I'm trying to convert a simple string in c to a double with:

 double n;
 sscanf_s(str, "%lf", &n);
 printf("%lf", n);

taking into account that:

const char *str[] = {"37107287533902102798797998220837590246510135740250"};

When I try to print n , the numbers is good until the 16th digit. The out is something like:

371072875339021043110257403....

What could be the problem?

Cesar Augusto
  • 255
  • 2
  • 10
  • because floating-point types in C have limited precision (~15-17 digits for [double-precision IEEE-754](https://en.wikipedia.org/wiki/Double-precision_floating-point_format)). [Double precision - decimal places](https://stackoverflow.com/q/9999221/995714). On some platforms you can use `long double` to get a few more digits though [Decimal Precision Lost after 15th Digit - Bad PI](https://stackoverflow.com/q/24485846/995714) – phuclv Jul 12 '18 at 04:09
  • Because floating point is kind of like scientific notation. Your number is represented internally as the binary equivalent of 3.710728753390210 x 10^49, and you only get about 15 digits past the decimal in the mantissa. – Steve Summit Jul 12 '18 at 10:02
  • There is no type under an ordinary compiler on an ordinary machine that will let you represent a number like 37107287533902102798797998220837590246510135740250 with full precision. (That number needs at least 165 bits.) You would have to use a separate arbitrary-precision library. – Steve Summit Jul 12 '18 at 10:07

1 Answers1

1

2 problems:

sscanf_s(str, "%lf", &n); expects a char *, not a char **. Enable all compiler warnings to see such problems and be sure to cut/paste problems correctly.

const char *str[] = {"37107287533902102798797998220837590246510135740250"};  

Did you mean the following?

const char *str = {"37107287533902102798797998220837590246510135740250"};

A double usually can exactly encode about 264 different values as a double is often a 64-bit piece of data.
37107287533902 102798797998220837590246510135740250 is not one of them.

Output like the following is reasonable:
37107287533902 1043110257403....

37107287533902 104311025740304689820495323650000000.0 is the closest representable double.

37107287533902 099118728881769862191964827320000000.0 would have been the next best choice.

Notice in this range, exact double are 2112 apart (about 5.2*1033). Such is the binary nature of most double encodings.

chux - Reinstate Monica
  • 113,725
  • 11
  • 107
  • 213