I get some homework, but i stack in it. Maybe you can help me. Task below.
Read the keyboard integer in the decimal system and establishment of a new system of numbers.
Output in the console number written in the new notation.
I made for 2 to 10 systems only and i can't make from 10 to 36. I tried to make in second loop something like this:
if ( result > 9 ) {
printf("%c", 55+number);
} else {
printf("%d", result);
}
my code:
#include <stdio.h>
int main() {
int number, base;
int i, result;
scanf("%d %d", &number, &base);
if ( number < base ) {
printf("%d\n", number);
} else {
for ( i = base; i <= number / base; i *= base );
for ( int j = i; j >= base; j /= base ) {
result = number / j;
printf("%d", result);
number = number % j;
}
printf("%d\n", number%base);
}
return 0;
}
else
condition needs some changes:
1. value to digit conversion needs to apply to the inner loop and to the final printf("%d\n", number % base)
. Instead of adding in both places, simply make your loop run to j > 0
, rather than j >= base
and only use the last printf()
for \n
.
2. Rather than using a magic number 55
use result - 10 + 'A'
. It easier to understand and does not depend on ASCII - (does depend on A, B, C ... being consecutive).
3. The rest is OK.
[edit]
@nos pointed out problem with if()
condition.
So remove if ( number < base ) { ... else {
and change for (i = base;
to for (i = 1;
making an even more simple solution.
// } else {
for (i = 1; i <= number / base; i *= base)
;
int j;
// for (j = i; j >= base; j /= base) {
for (j = i; j > 0; j /= base) {
result = number / j;
#if 1
if (result > 9) {
// printf("%c", 55 + result);
printf("%c", result - 10 + 'A');
} else {
printf("%d", result);
}
#else
printf("%d", result);
#endif
number = number % j;
}
printf("\n");
// }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With