Question

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
Was it helpful?

Solution

Your output is broken. You're actually writing the value of d twice in the following code:

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);

If you'd written this:

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);

Then you'd have the output:

d = 1.500000
t = 1, nsec = 0.000000

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, a long. Make nsec a float instead.

OTHER TIPS

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.

You're trying to assign .5 to a long which isn't going to happen.

double d = 1.5;
int i = (int)d;
double j = d - (double)i;

printf("%d %f\n",i,j);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top