简体   繁体   English

我的函数返回了错误的double值(C)

[英]My function is returning the wrong double value (C)

So my code is relatively simple, I am just attempting to get a double from a file (input.dat). 所以我的代码相对简单,我只是想从文件(input.dat)中获取双精度字。 I am getting the double, however when I return in to main, I get a different value for some reason. 我获得了双倍奖励,但是当我返回main时,由于某种原因,我得到了一个不同的值。 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.dat input.dat中实际上是什么

11234567.0 11234567.0

So when I run the program, the print statement in read_double is printing the correct number. 因此,当我运行程序时,read_double中的print语句将打印正确的数字。 But when I return that to main, and print it in main, it's printing to 16.000. 但是,当我将其返回给main并在main中打印时,它的打印速度为16.000。

When I get rid of the print statement that's in read_double, then main prints 1.000. 当我摆脱了read_double中的print语句时,main将打印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. 任何帮助表示赞赏,谢谢。

You need to declare the return type of your read_double() function in the source file that defines main(), or in an included header. 您需要在定义main()的源文件中或包含的标头中声明read_double()函数的返回类型。 Otherwise, C doesn't "know" it returns a floating point double type. 否则,C不会“知道”它返回浮点双精度类型。

double read_double(FILE *infile);

int main(void) { ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM