Given the following
Code:
include <stdio.h>
int main(void)
{
int part1, part4;
float part2;
char part3[6];
char s[]="1234.56abc 903";
sscanf(s, "%2d%5e%5s%d", &part1, &part2, part3, &part4);
printf("parse string: %s\n", s);
printf("part1=%d\n", part1);
printf("part2=%f\n", part2);
printf("part3=%s\n", part3);
printf("part4=%d\n", part4);
return 0;
}
The corresponding output is:
$./fl
parse string: 1234.56abc 903
part1=12
part2=34.560001
part3=abc
part4=903
The way I've always understood it, the 1 in part2 appears because the conversion from binary to decimal is only exact when dealing with a power of 2. This includes fractional parts.
Now I change float to double
Code:
#include <stdio.h>
int main(void)
{
int part1, part4;
double part2;
char part3[6];
char s[]="1234.56abc 903";
sscanf(s, "%2d%5le%5s%d", &part1, &part2, part3, &part4);
printf("parse string: %s\n", s);
printf("part1=%d\n", part1);
printf("part2=%f\n", part2);
printf("part3=%s\n", part3);
printf("part4=%d\n", part4);
return 0;
}
The corresponding output is now:
$./fl
parse string: 1234.56abc 903
part1=12
part2=34.560000
part3=abc
part4=903
The question is why doesn't the 1 appear in part 2 anymore? Is this because double has a longer precision? If I would have the computer print out the decimal spot to say 16 spots, would the 1 appear again?