开发者

How can i delete 2 digits in an unsigned int?

So I have a 1.40 number, and I want to delete the 1., so I can convert the 40 to a binary 开发者_如何学Gonumber. How can I just delete 2 digits?


The only sane way to do what you want is:

double x = 1.40;
int i;
snprintf(buf, sizeof buf, "%.2f", x);
i = atoi(buf+2);

This looks ugly and horribly inefficient, but the problem with other approaches is that 1.40 does not exist in binary floating point. Instead, 1.40 evaluates to the nearest existant floating point value, which may be slightly less or slightly greater than 1.40. If it's less, things like (int)(x*100) will give you 139 instead of 140.

Using snprintf at least ensures that the same semantics that would be used for displaying the value get used in evaluating it.

Of course what you're doing probably doesn't make sense to begin with. Is 1.40 dollars and cents (or similar in other currency)? If so, you should simply be storing an integer number of cents to begin with. Floating point should never be used for currency.


Assuming 1.40 is stored as a floating point or double:

double x = 1.40;
int hundreths = (int)(x * 100) % 100;


One approach is to take the input as a floating pointer number, then subtract the integral part and multiply by 100:

unsigned int v = (my_double - floor(my_double)) * 100

Note: using floor like this ensures the calculation works even if my_double is outside the range INT_MIN..INT_MAX.

Another approach is to take the input as a string, skip to the first ., and convert the rest...

const char* p = strchr(my_input, '.');
if (p)
{
    unsigned int v = atoi(p + 1);
    // use v...
}


I am not a C programmer, but I think I didn't make any mistakes:

double y = x - floor(x);
while(y - floor(y) != 0.0){
    y *= 10.0;
    // y %= 10.0, which is
    y -= floor(y / 10) * y

    // The current digit is:
    // floor(y)
    // Push it to a character array or whatever you wanna do.
    // The order for 1.45 is: 4 then 5, for 1.40 it's only 4
}


I think ur trying to figure out the binary form of any number and for which u actually don`t need to split it.

But if u do need it, here you go ...

#include<iostream.h> 
int main()
{
    double i = 2.40;
    unsigned int j;
    float k;
    j = (int) i / 1;
    k =  i - j ; 
    cout << k;
    return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜