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?

``````int numdigits(int x)
{
int t = x, n = 1;
while(t>= 10)
{
n++;
t = t/10;
}
return n;
}``````
3
Contributors
4
Replies
5
Views
10 Years
Discussion Span
Last Post by Narue

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.