Domanda

I try to convert any number base from 10 base. After I multiply two numbers that the same base, but the function should be recursive.

    double convert(int number,int base)
{
    int digit = 1;
    double sum=0;
    int i=0;
    int figure;
    double end;
    if(base==10)
        return number;

    else
    {
        figure = (digit % (digit * 10) - number % digit) / digit;
        end=pow(base,i);
        sum+=figure*end;
        ++i;
        digit *= 10;

        convert(figure,base);

    }
return sum;
}

But I'm confused in else, it doesn't work. How can I fix it? Any offers? Thanks..

È stato utile?

Soluzione

E.g.

#include <stdio.h>

int convert(int number,int base){
    if(number == 0 || base==10)
        return number;

    return (number % base) + 10*convert(number / base, base);
}

int main () {
    int i;
    for(i=2;i<=10;++i)
        printf("%d is %d base(%d)\n", 100, convert(100, i), i);
    return 0;
}

Altri suggerimenti

static string ToBase(int n, int @base)
    {
        Func<int, string, string> x = null;
        return (x = (i, j) => 
        {
            if (i == 0)
            {
                return j;
            }
            return x(i / @base, i % @base + j);
        })(n, string.Empty);
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top