"); scanf("%d", &base5_v); int remainder = base5_v % 10; base5_" /> "); scanf("%d", &base5_v); int remainder = base5_v % 10; base5_" /> "); scanf("%d", &base5_v); int remainder = base5_v % 10; base5_"/>

Can't get the output I need

53 Views Asked by At
#include <stdio.h>
#include <math.h>

int main(){

    int base5_v;
    int digit = 0; 

    printf("> ");
    scanf("%d", &base5_v);

    int remainder = base5_v % 10;
    base5_v /= 10;

    int base10_v = remainder * (int) powf(5, digit++);

    remainder = base5_v % 10;
    base5_v /= 10;

    base10_v += remainder * (int) powf(5, digit++);

    remainder = base5_v % 10;

    base10_v += remainder * (int) powf(5, digit++);

    printf("%d in base 5 is %d in base 10\n", base5_v, base10_v);

    return 0;
}

So I am having a hard time finding the issue in this code. the output is supposed to be like this after I input my number:

144 in base 5 is 49 in base 10

but when I compiled and ran the code it looked like this:

1 in base 5 is 49 in base 10

Can I get some help on what is wrong and how I can fix it?

1

There are 1 best solutions below

0
Angs On

Your code modifies base5_v each time it runs base5_v /= 10;.

In your example, you pass 144 as an input. The first time, it modified the value as 14 after the modulus operation, the second time 1 is left after modulus.

I think the biggest mistake in your code is not to use any loop. What'd happen if the user would enter 1234 or another digit length? There are many ways how you could have coded it, but this is one of them (ignoring the user input validation):

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>

#define MAX_DIGIT_LENGTH    10

int main()
{
    char base5_v[MAX_DIGIT_LENGTH] = { '\0' };

    printf("> ");
    scanf("%s", base5_v);

    int base10_v     = 0;
    int digit_length = (int)strlen(base5_v);
    for (int digit = 0; digit < digit_length; digit++)
    {
        base10_v += pow(5, digit) * (base5_v[digit_length - digit - 1] - '0');
    }
    printf("%s in base 5 is %d in base 10\n", base5_v, base10_v);

    return 0;
}