【发布时间】:2010-12-29 18:46:48
【问题描述】:
作为作业问题,我正在从标准输入读取十进制整数,将其转换为不同的基数(也从标准输入提供)并将其打印到屏幕上。
这是我目前所得到的:
#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;
}
这很好用,只是它使用的算法计算从最低有效位到最高有效位的转换数字,从而将其反向打印。因此,例如,将 1020 转换为十六进制 (0x3FC ) 将打印 CF3。
我可以使用什么技巧来反转这些数字以按正确的顺序打印。我只能使用 if-else,而简单的数学运算符和 printf()/getchar()/scanf() - 不能使用函数、数组或指针。谢谢。
【问题讨论】:
-
+1 代码简洁。不错的第一次尝试。
-
谢谢 - 我实际上已经完成了很多编码工作,但其中大部分是 python、ruby 和 c#.. 所以我真的不能把第一次尝试归功于 ;)跨度>
-
我认为,您应该发出警告(错误?)。如果基数高于 37,您将打印出特殊字符...当基数高于 255 时,您的程序会如何运行...您将打印出什么?
-
我实际上更关心 base == 0