문제

I have two numbers:

1234567890 <--- Long

and

0.123456 <--- Float

Is there any way to combine these to make a float(or double) in the following format:

(123)4567890.123456

I don't mind if the numbers in brackets have to be removed.

도움이 되었습니까?

해결책

Given a long l and a float f, you can use:

double result = l % 10000000 + (double) f;

This will usually lose some accuracy in the fraction portion.

Update: From a comment, we learn that these values are a time represented as a number of seconds and a fraction of a second and that it is desired to calculate an interval. If we want to find the difference between two times, then we can calculate the difference with fewer problems from accuracy and precision this way:

double SubtractTimes(long l0, float f0, long l1, float f1)
{
    long ld = l1 - l0;
    double fd = (double) f1 - f0;
    return ld + fd;
}

Note: If there is a concern that the time may have wrapped around some upper limit, then the code should test for this and make adjustments.

다른 팁

I must be missing something. Isn't it as easy as this?

long l = 1234567890;
float f = 0.123456;

float result = l + f;

Use this:

double result = l + f;
printf("%.6f",result);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top