我正在学习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()来交换其他数制?
感谢您的阅读。
请您参考如下方法:
要将评论中的建议之一付诸实现:
#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);
}
