c - 用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()交换其他数字系统?
感谢您的阅读。
解决方案
要将评论中的一项建议付诸实践:
#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);
}
推荐阅读
- javascript - 使 JS 类可调用而没有副作用
- elasticsearch - 如何在 ELK Stack 中为 filebeat 创建弹性搜索索引?
- android - 删除列表项后随机检查带有 Kotlin recyclerView 的 Android
- c++ - 重定位 .debug_line 部分中的文件
- html - 在引导容器中包装多个部分的正确方法是什么?
- java - 为什么我的 spark 连接器包的 maven 子依赖版本与其他版本不同
- javascript - 为什么类星体框架选择 css 中的这种奇怪行为?
- python - 如何在张量流中创建特征列?
- r - 如何摆脱软件包 e1071 安装错误?
- python - 如何从列表或字典中向子图添加标题?