DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C (http://www.daniweb.com/forums/forum118.html)
-   -   number of digits in a base (http://www.daniweb.com/forums/thread144582.html)

winky Sep 8th, 2008 4:17 am
number of digits in a base
 
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;
}

Ancient Dragon Sep 8th, 2008 4:37 am
Re: number of digits in a base
 
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.

winky Sep 8th, 2008 4:42 am
Re: number of digits in a base
 
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.

Ancient Dragon Sep 8th, 2008 5:01 am
Re: number of digits in a 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.

Narue Sep 8th, 2008 10:26 am
Re: number of digits in a base
 
>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.


All times are GMT -4. The time now is 7:37 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC