首页 > 解决方案 > 用C语言交换号码系统?

问题描述

我正在学习 C 语言,但我有一个问题。我想做这样的程序,

input number :

输入数字后,例如如果我输入 32165 则计算机显示

The decimal 32165 is the octal number 076645, and the hexadecimal number is 0x7da5.
The octal number 32165 is the decimal 13429, and the hexadecimal number is 0x3475.
The hexadecimal number 32165 is the decimal 205157, and the octal number is 0620545.

我可以做这样的第一行

#include <stdio.h>

int main()
{
    printf("input number: ");
    int num;
    scanf("%d", &num);
    printf("The decimal %d is the octal number %o, and the hexadecimal number is %x.", num, num, num);
}

但我不知道如何做第二,第三行。

如何只使用一个scanf()交换其他数字系统?

感谢您的阅读。

标签: c

解决方案


要将评论中的一项建议付诸实践:

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

enum { MAX_NUM_LENGTH = 100 };

int main(void)
{
    char buffer[MAX_NUM_LENGTH + 1];

    int number;
    printf("Input number: ");
    if (!scanf("%d", &number)) {
        fputs("Input error!\n\n", stderr);
        return EXIT_FAILURE;
    }

    printf("The decimal number %d is the octal number 0%o, "
           "and the hexadecimal number is 0x%x.\n", number, number, number);

    int temp;
    sprintf(buffer, "%d", number);
    sscanf(buffer, "%o", &temp);

    printf("The octal number 0%o is the decimal number %d, "
           "and the hexadecimal number is 0x%x.\n", temp, temp, temp);

    sprintf(buffer, "%d", number);
    sscanf(buffer, "%x", &temp);

    printf("The hexadecimal number 0x%x is the decimal number %d, "
           "and the octal number is 0%o.\n", temp, temp, temp);
}

推荐阅读