简体   繁体   中英

C++ How do I set the fractional part of a float?

I know how to get the fractional part of a float but I don't know how to set it. I have two integers returned by a function, one holds the integer and the other holds the fractional part. For example:

int a = 12;
int b = 2; // This can never be 02, 03 etc
float c;

How do I get c to become 12.2? I know I could add something like (float)b \\ 10 but then what if b is >= than 10? Then I would have to divide by 100, and so on. Is there a function or something where I can do setfractional(c, b) ?

Thanks

edit: The more I think about this problem the more I realize how illogical it is. if b == 1 then it would be 12.1 but if b == 10 it would also be 12.1 so I don't know how I'm going to handle this. I'm guessing the function never returns a number >= 10 for fractional but I don't know.

The most trivial method would be counting the digits of b and then divide accordingly:

int i = 10;
while(b > i) // rather slow, there are faster ways
    i*= 10;

c = a + static_cast<float>(b)/i;

Note that due to the nature of float the result might not be what you expected. Also, if you want something like 3.004 you can modify the initial value of i to another power of ten.

Something like:

float IntFrac(int integer, int frac)
{
    float integer2 = integer;
    float frac2 = frac;

    float log10 = log10f(frac2 + 1.0f);
    float ceil = ceilf(log10);
    float pow = powf(10.0f, -ceil);

    float res = abs(integer);
    res += frac2 * pow;

    if (integer < 0)
    {
        res = -res;
    }

    return res;
}

Ideone: http://ideone.com/iwG8UO

It's like saying: log10(98 + 1) = log10(99) = 1.995, ceilf(1.995) = 2, powf(10, -2) = 0.01, 99 * 0.01 = 0.99, and then 12 + 0.99 = 12.99 and then we check for the sign.

And let's hope the vagaries of IEEE 754 float math won't hit too hard :-)

I'll add that it would be probably better to use double instead of float . Other than 3d graphics, there are very few fields were using float is a good idea nowadays.

kindly try this below code after including include math.h and stdlib.h file:

 int a=12;

 int b=22;

 int d=b;

 int i=0;

 float c;

while(d>0)

{

d/=10;

i++;

}

c=a+(float)b/pow(10,i);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM