标签云

微信群

扫码加入我们

WeChat QR Code

So my code is relatively simple, I am just attempting to get a double from a file (input.dat). I am getting the double, however when I return in to main, I get a different value for some reason. Here's the code:int main(void) {FILE *infile;infile = fopen("input.dat", "r");double data = read_double(infile);printf("%lf", data);return 0;}double read_double(FILE *infile) {double data = 0;//infile = fopen("input.dat", "r");fscanf(infile, "%lf", &data);printf("%lf\n", data);return data;}What's actually in input.dat11234567.0So when I run the program, the print statement in read_double is printing the correct number. But when I return that to main, and print it in main, it's printing to 16.000. When I get rid of the print statement that's in read_double, then main prints 1.000. I don't really know what to do right now, I'm wondering if this has something to do with the way that data is stored and transferred? Any help is appreciated, thank you.


My crystal ball tells me you never prototyped read_double to return double prior to its invoke in main. Therefore your compiler assumes it is a variable-argument function of the form int func(), and you compiler warnings are either too low, or you're ignoring the ensuing "implicit declaration of function returning int" text in your build. That crystal ball also indicates these two functions are in different source files, otherwise the compiler would have complained about "error: conflicting types for ‘read_double’", and your code shouldn't have even compiled.

2019年04月25日55分19秒

Note that C99 says your program is ill-formed because you do not ensure that read_double() is declared or defined before it is used.If your compiler did not complain, you need to find out how to turn on the compilation warnings, or persuade it that C99 is an old standard (C11 is newer; C18 is newest, but is mainly minor corrections to C11 rather than any startlingly new technology).And heed any warnings it does give.If it still doesn't give good warnings, get a better compiler.

2019年04月25日55分19秒