putchar可以打印整数吗?
如何在putchar
的帮助下打印整数。 我想在不使用外部存储的情况下这样做。
去年在一次采访中提出了这个问题。
面对面试时的模糊要求时,表达您的假设是个好主意。
我会考虑只能使用putchar
来表示它是我唯一允许调用的库函数。 我还假设“没有外部存储”意味着我无法显式创建缓冲区。 如果面试官同意我的假设,我会继续:
void pr_int(int n) { if (n < 0) { putchar('-'); n = -n; } if (n / 10 != 0) pr_int(n / 10); putchar((n % 10) + '0'); }
如果面试官然后评论说n = -n;
对于INT_MIN
会失败,如下所述,然后我会将其重写为:
void pr_uint(unsigned int n) { if (n / 10 != 0) pr_uint(n / 10); putchar((n % 10) + '0'); } void pr_int(int n) { if (n < 0) { putchar('-'); n = -n; } pr_uint((unsigned int) n); }
考虑使用itoa函数(您需要导入其库),然后循环遍历它生成的cstring中的每个字符(使用strlen来获取此循环的上限),然后在每个字符上使用putchar()。
正确回答这个问题在很大程度上取决于“外部存储”和“仅限putchar
”的含义。
void print_int_r (int x, int neg) { int y = x/10; int d = x%10; if (y) print_int_r(y, neg); putchar('0' + (neg ? -d : d)); } void print_int (int x) { int neg = x < 0; if (neg) putchar('-'); print_int_r(x, neg); putchar('\n'); }
上面的实现假设C99语义,如C99第6.5.5节p6中所述:
当整数被划分时,
/
运算符的结果是代数商,丢弃任何小数部分。 如果商a/b
是可表示的,则表达式(a/b)*b + a%b
应等于a
。
但是, %
C的ANSI C(C 89)语义更差。 ANSI C第3.3.5节p5说:
如果任一操作数为负,则
/
运算符的结果是小于代数商的最大整数还是大于代数商的最小整数是实现定义的,这是%
运算符的结果的符号。
Ferruccio的第二个答案几乎是完美的。 问题是转换不对。 如果操作的结果是int
无法表示的值,则n = -n
的结果是未定义的。 所以,转换应该这样做:
void pr_int(int n) { if (n < 0) { putchar('-'); pr_uint(-(unsigned int)n); } else pr_uint(n); putchar('\n'); }
现在解决方案符合所有ISO C标准。 细节可以在这里找到。
已经有类似这样的问题了,我回答了这个问题。
将它转换为仅使用putchar的程序应该很容易(例如,执行以下操作:
while(buf[i]) putc(buf[i++]); putc('\n');
我刚收集了一些可怕的东西。 它主要是概念validation,它非常可怕 ,仅适用于正整数,但几乎不使用存储。 啊,整数也不能太大,而且它可能是错误的。
#include #include int main() { const int max_precision = 100000; int b = 7414; int max = b * max_precision; assert(b > 0); while (b <= max && b >= 0) { putchar('0' + (b / max_precision) % 10); b *= 10; } putchar('\n'); }
max_precision
设置要打印的位数。 b
存储实际数字, max
用于终止循环(或者整数溢出)。