这段代码出了什么问题?

时间:2011-04-26 14:31:00

标签: c return-value precision

在下面的代码中发生了一件奇怪的事情。函数get_time_in_seconds(),我自己构建并独立测试的自定义函数,直接从long printf语句中调用时工作正常。但是,当我将其分配给变量curr_time2时,它不会存储期望值。任何猜测为什么?

while (1)
{
    count++;
    bytes_read = recvfrom(sock,recv_data,1024,0,(struct sockaddr *)&client_addr, (socklen_t*)&addr_len);
  recv_data[bytes_read] = '\0';
  strcpy(buff,inet_ntoa(client_addr.sin_addr));
    printf("\nAt %lf (%s , %d, Num : %d) said : ",get_time_in_seconds(),buff,ntohs(client_addr.sin_port),get_id(buff));
    printf("%s", recv_data);
    curr_time2=get_time_in_seconds();
    printf("%lf\n",curr_time2);
//      data.nodeid=get_id(buff);
//      data.time = curr_time2;
    //printf("%f,%f\n",data.time,curr_time2);
    store_packetdata(&data);
    fflush(stdout);
}

示例输出:

  

1303829191.827888(10.22.6.162,   35355,Num:1)说:505   1303829248.000000

     

在1303829196.827893(10.22.6.162,   35355,Num:1)说:506   1303829248.000000

     

1303829201.827898(10.22.6.162,   35355,Num:1)说:507   1303829248.000000

     

在1303829206.827903(10.22.6.162,   35355,Num:1)说:508   1303829248.000000

     

1303829211.827908(10.22.6.162,   35355,Num:1)说:509   1303829248.000000

     

在1303829216.827913(10.22.6.162,   35355,Num:1)说:510   1303829248.000000

     

在1303829221.827918(10.22.6.162,   35355,Num:1)说:511   1303829248.000000

     

在1303829226.827923(10.22.6.162,   35355,Num:1)说:512   1303829248.000000

     

1303829231.827928(10.22.6.162,   35355,Num:1)说:513   1303829248.000000

在1303829236.827933(10.22.6.162,35355,Num:1)说:514 1303829248.000000

1303829241.827938(10.22.6.162,35355,Num:1)说:515 1303829248.000000

编辑:我现在已经解决了这个问题。最初,curr_time2和get_time_in_sconds()的返回类型都在float中。当我将两者转换为双倍时,代码开始工作。但是,我想知道的是为什么printf()打印准确,而curr_time2只存储了值的近似值。

新声明(对于旧声明,将double更改为float)。

double get_time_in_seconds()
{
    gettimeofday(&tv, NULL);
    double retval= (double)tv.tv_sec + ((double)tv.tv_sec)/1000000;
    return retval;
}
    static double curr_time2=0.0;

3 个答案:

答案 0 :(得分:2)

在不知道curr_time2的类型的情况下我只能猜测,但它似乎被声明为整数而不是浮点数。

如果不是这种情况,请发布更多代码(函数和参数声明),因为此刻我不能做更多的猜测。

答案 1 :(得分:1)

编辑后

  

>为什么printf()打印准确

函数printf()是一个可变函数 参数“遭受”默认转换:基本上charshortint; floatdouble

在您的代码中

printf("%lf", float_value);

float_value自动转换为double%lf转换规范与C99中%f的处理方式相同("%lf"是C89中的错误)期望double值。

答案 2 :(得分:1)

大多数C编译器实际上不会将float值作为参数传递或从函数返回它们 - 它们将默默地转换为double。因此,当您直接将get_time_in_seconds()的返回值传递给printf时,它以双精度完成。但是,当您将其存储在float变量curr_time2中时,它会将其转换为商店的单精度,然后返回双精度以传递给printf。

请注意,以上是规范允许的行为,但不是必需的行为 - C编译器总是允许(通过规范)对中间值使用额外的精度,例如函数参数和返回值

相关问题