Converting a fraction into other numeral system

Hi there,

I get a fraction in decimal and my job is to convert it into other numeral system (< 10).

Can you give me a clue how can I do this ?
I also found this pdf:

http://www.freeinfosociety.com/pdfs/computers/15binnumbers.pdf?phpMyAdmin=af0f6b4465fe3f904426eaeb3dc0e3fa&phpMyAdmin=Kb2XHnhmhTctZwPmOqks7zD3-sc

Page 5. Can you explain me what does Record the "carry" across the decimal point means ?
Well, if you have a number 0.7, multiply it by 2 and get 1.4 they call that 1 a carry. Recording it across the decimal point probably means appending it to the end of the result.
Is it good ? :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void foo(float fraction, const int& system)
{
    int digit;

    fraction -= static_cast<int>(fraction);

    cout << ".";

    while(fraction != 0)
    {
        fraction *= system;
        digit = static_cast<int>(fraction);
        fraction -= digit;
        cout << digit;
    }
}
It seems ok.. Does it work?

const & is used for objects that are too big to copy (and will not be changed by the function). There is no gain in passing system as const int&. A plain int would be fine (or better).

Instead of static_cast<int>(fraction), you could write (int)fraction.

Note that some (many in binary) of the fractions you try will be infinite (periodic). Your code does not handle such case. You should have a set maximum number of digits.
You should have a set maximum number of digits.


How can I know what this maximum number should be ?
That's for you to decide.
If you want to find the period of the fraction, I really have no idea how (except the brutal approach) and it's probably quite complicated..
Topic archived. No new replies allowed.