| number-in-base.c - Et C program der omregner et tal fra titalsystemet til et andet talsystem og udskriver resultatet. | Lektion 4 - slide 11 : 13 Program 2 |
#include <stdio.h>
void print_in_base(int, int);
int main(void) {
int i, n, base;
for (i = 1; i <= 5; i++){
printf("Enter positive decimal number "
"and number base (at least two): ");
scanf(" %d %d", &n, &base);
print_in_base(n, base); printf("\n");
}
return 0;
}
/* Convert the decimal number n to base and print the result */
void print_in_base(int n, int base){
int ciffer;
if (n > 0){
ciffer = n % base; /* find least significant ciffer */
/* RECURSIVELY, find and print most significant ciffers */
print_in_base(n / base, base);
/* print least significant ciffer */
if (ciffer >= 0 && ciffer <= 9)
putchar('0' + ciffer);
else if (ciffer >= 10 && ciffer <= 36)
putchar('a' + ciffer - 10);
else putchar('?');
}
}