使用 time_t 解析用户输入
我的想法是,如果用户输入 t = 2.5,那么我将 2 和 0.5 分别提取到 2 个不同的变量中。但我无法做到这一点。
这是代码:
$ 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
My idea is, if user enters t = 2.5
, then I extract 2 and 0.5 separately in 2 different variables. But I am unable to do that.
Here is the code:
$ 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);
}
Output is:
# ./a.out
d = 1.500000
t = 0, nsec = 0.000000
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的输出坏了。实际上,您在以下代码中写入了两次
d
的值:如果您这样写:
那么您将得到输出:
现在可以更清楚地看出您有舍入错误。在这种情况下,您可以通过将 0.5 分配给
nsec
(一个long
)来舍弃所有小数位。将nsec
改为float
。Your output is broken. You're actually writing the value of
d
twice in the following code:If you'd written this:
Then you'd have the output:
It's now clearer that you have a rounding error. In this case, you cast away all the decimal places by assigning 0.5 to
nsec
, along
. Makensec
afloat
instead.您还尝试在 long 中存储小数值。您需要将其乘以 1000 或将
nsec
设为双精度。nsec=d-(double)((time_t)d);
如果 d 为 1.5,则右侧的结果将为 0.5,当它存储在 nsec 中时,它会隐式向下转换为 0 。
You are also trying to store a fractional value in a long. You either need to multiply this by 1000 or make
nsec
a double.nsec=d-(double)((time_t)d);
If d is 1.5, the result of the right hand side would be 0.5, which will implicitly cast down to 0 when it gets stored in nsec.
您尝试将
.5
分配给long
,但这不会发生。You're trying to assign
.5
to along
which isn't going to happen.