문제

How can I transform rational numbers like 1.24234 or 45.314 into integers like 124234 or 45314 also getting the number of decimal digits?

도움이 되었습니까?

해결책

Convert to a string

Find the position of the decimal point.

Subtract that from the length of the above string, for the number of decimals.

Then take the point out of the string.

다른 팁

int i=0;
float a = 1.24234;

for(i; i<20; i++){
    float b=pow(10,i);
    if((a*b)%10==0)
        break;
}
int c = pow(10,i-1);
int result = a*c;

I think this code will help you.

If your number is W.D (Whole.Decimal)

To get W just do (int)W.D. To get D you can do W.D - (int) W.D

Now you have your whole number and your decimal point separated. To figure out your x10 multiplier on your W keep dividing D by 10 until you get a result that is less than 10.

Now: WxN+D (where N is the number of times you divided by 10)

Note: I didn't write the code as an example, because I feel this may be a homework assignment. Also, if you are using very long (ie: precise floating points) this won't hold, and could likely overflow. Check your bounds before implementing something like this.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top