0

This would be the part where I do the readings

do {
    res=0;
    res += fscanf(in , "%50s",recs[n].city); 
    res += fscanf(in , "%d.%d.%d ", &recs[n].d.d , &recs[n].d.m , &recs[n].d.y);
    res += fscanf(in , "%f", &recs[n].t );
    recs = realloc(recs, (n+2)*68);
    if(!recs){
        printf("Error for second recs");
        return 0;
    }
    n++;
        }while(res == 5);

My input file :

Germany 8.01.2020 54.24
Romania 1.2.2019 34.55
Banat 5.1.1999 41.66
Region 4.5.2023 51.71
Idk 12.11.1967 91.981

My output :

Germany 8 1 2020 54.240002 
Romania 1 2 2019 34.549999 
Banat 5 1 1999 41.660000 
Region 4 5 2023 51.709999 
Idk 12 11 1967 91.981003  

So basically my question is why does fscanf reads 51.709999 instead of 51.71 for example.

  • 3
    [Is floating point math broken?](//stackoverflow.com/q/588004) – 001 Jan 09 '20 at 17:40
  • What is the [magic number](https://en.wikipedia.org/wiki/Magic_number_(programming)) `68` representing? Assuming it's the (calculated) size of a structure, then please read [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) – Some programmer dude Jan 09 '20 at 17:42
  • It won't look so bad if you output with `"%.2f"` for two decimal places. It will also be more (but not completely) accurate if you use `double` instead of the inferior `float`, and `"%lf"` in `fscanf`. Or store the last field as a string to reproduce it exactly, I see one has 3 decimal places. – Weather Vane Jan 09 '20 at 17:49
  • Thx Johnny for the floating point math it was useful. – Dragos Surugiu Jan 09 '20 at 17:51
  • and for the magic number yes it the size of a structure and I have initially used the sizeof(structure) , however I would get a reallocation() error. – Dragos Surugiu Jan 09 '20 at 17:52
  • Then that sounds like the subject of another question. Magic numbers are bad, especially considering the link in my previous comment. – Some programmer dude Jan 09 '20 at 17:54
  • Note that you can use a precision specification in the conversion - `%.2f` will print the floating point value out to 2 decimal places, which *should* give you the value you expect. The default is 6 decimal places. – John Bode Jan 09 '20 at 17:58
  • Got rid of the 'magic number' thing and the program is working properly thanks for all the tips and good info . – Dragos Surugiu Jan 09 '20 at 21:38

1 Answers1

0

In the end my problem was not the understanding the floating point math behind .So anybody encountering this should get some knowledge about it or simply printing the first decimals of the float number.