Problems with hex

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("%dn", 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("%dn", 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("%dn", 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");
  // }

int number, base;
scanf("%d %d", &number, &base);

int divisor = base;
while (divisor <= number)
    divisor *= base;

while (divisor != 1) {
    divisor /= base;
    int digit = number / divisor;
    number -= digit * divisor;
    printf("%c", digit <= 9 ? digit + '0' : digit + 'A' - 10);
}
printf("n");
return 0;

警告:数字大于200000000的未定义行为。


You're on the right track and are very close to the answer. Your program is printing the resulting digits in two places.

I suggest making a single function to output the digits and using it in both places:

void print_digit(int number) {
  // your code here
}
链接地址: http://www.djcxy.com/p/74296.html

上一篇: 使用Linphone的Android SIP应用程序

下一篇: 问题与十六进制