我的想法是,如果用户输入t = 2.5
,那么我在2个不同的变量中分别提取2和0.5。但我无法做到这一点。
以下是代码:
$ export LT_LEAK_START=1.5
$ echo $LT_LEAK_START
1.5
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
double d;
time_t t;
long nsec;
d=strtod(getenv("LT_LEAK_START"), NULL);
t=(time_t)d;
nsec=d-(double)((time_t)d); // Extract fractional part as time_t always whole no.
printf("d = %lf\n",d);
printf("t = %u, nsec = %f\n",d,nsec);
}
输出是:
# ./a.out
d = 1.500000
t = 0, nsec = 0.000000
答案 0 :(得分:1)
您的输出已损坏。您实际上在以下代码中将d
的值写入两次:
nsec=d-(double)((time_t)d); // Extract fractional part as time_t always whole no.
printf("d = %lf\n",d);
printf("t = %u, nsec = %f\n",d,nsec);
如果你写了这个:
nsec=d-(double)((time_t)d); // Extract fractional part as time_t always whole no.
printf("d = %lf\n",d);
printf("t = %u, nsec = %f\n",t,nsec);
然后你有输出:
d = 1.500000
t = 1, nsec = 0.000000
现在更清楚的是你有一个舍入误差。在这种情况下,您通过将nsec
long
分配给nsec
来丢弃所有小数位。将float
改为{{1}}。
答案 1 :(得分:0)
您正在尝试将.5
分配给long
,但这不会发生。
double d = 1.5;
int i = (int)d;
double j = d - (double)i;
printf("%d %f\n",i,j);
答案 2 :(得分:0)
您还试图在长整数中存储小数值。您需要将此乘以1000或使nsec
成为双倍。
nsec=d-(double)((time_t)d);
如果d为1.5,右侧的结果将为0.5,当它以nsec存储时将隐式地转换为0。