作为一个家庭作业问题,我正在从stdin读取十进制int,将其转换为另一个基础(也是从stdin提供)并将其打印到屏幕上.
这是我到目前为止所得到的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, base, remainder, quotient;
printf("please enter a positive number to convert: ");
scanf("%d", &num);
printf("please enter the base to convert to: ");
scanf("%d", &base);
remainder = quotient = 1;
// validate input
if (num < 0 || base < 0) {
printf("Error - all numbers must be positive integers!\n");
return 1;
}
// keep dividing to find remainders
while (quotient > 0) {
remainder = num % base;
quotient = num / base;
num = quotient;
if (remainder >= 10) {
printf("%c", remainder + 55);
} else {
printf("%d", remainder);
}
}
printf("\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这很有效,只是它使用的算法计算从最低有效数字到最高有效数字的转换数字,从而反向打印.因此,例如,将1020转换为十六进制(0x3FC)将打印CF3.
是否有一个技巧可以用来反转这些数字以正确的顺序打印.我只能使用if-else,而简单的数学运算符和printf()/ getchar()/ scanf() - 没有函数,数组或指针.谢谢.
(此处删除了帖子的原始部分,因为这不是解决方案)
那么我能看到的唯一解决方案就是执行您现在拥有的数字次数的循环。
因此,首先计算所有数字,直到最后一个数字,然后打印它。
然后你取原始值+基数并再次开始除法,直到到达第二个“最高值”数字,然后打印它。
这是一个双循环,您将所有内容计算两次,但不使用额外的存储空间。
| 归档时间: |
|
| 查看次数: |
6476 次 |
| 最近记录: |