I am supposed to rewrite the code below to "compute the number of digits to any base(such as base 2, base 16, base 8)." Just wondering if any of you can provide any explanation or pseudocode on how to go about doing this?

Thanks for any help you can give :).

int numdigits(int x)
{
int t = x, n = 1;
    while(t>= 10)
    {
         n++;
         t = t/10;
     }
     return n;
}

Recommended Answers

All 4 Replies

you must mean the number of digits in a number,
You're program is almost right, except the while statement should check for t > 0, not t >= 10. That function doesn't need variable t at all, just use the parameter variable x.

The code that I wrote is supplied to us; we are supposed to change it, so that it computes the number of digits to any base. I don't exactly understand what that means or how I would go about doing that.

At first, I thought it was asking how many digits are in a particular base( i.e. base 8 has 8 digits in its alphabet [0-7]), but that seems too easy.

I believe it wants us to write a program that we input a number, and we have to be able to output how many digits are output to a particular base.

I guess you would have to convert the number to a string and then return the length of the string. For example hex digits can't be represented by a simple integer -- only strings.

>I believe it wants us to write a program that we input a number, and we
>have to be able to output how many digits are output to a particular base.
That's trivial too. numdigits as it stands is specific to decimal only because it uses literal 10's in the loop condition and division step.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.