[英]How can I print the last digit of INT_MIN integer using putchar only?
我不允許使用 abs 或任何其他庫。 這是我到目前為止所嘗試的。
#include <stdio.h>
#include <limits.h>
int main()
{
int n = INT_MIN;
if (n == INT_MIN)
{
int a = -n;
a = n % 10;
putchar(a + '0');
}
return (0);
}
output 始終是“(”而不是正確答案。
首先將模數應用於負數以獲得單個負數。 否定那個。
#include <stdio.h>
#include <limits.h>
int main()
{
int n = INT_MIN;
int a = -( n % 10);
putchar(a + '0');
return (0);
}
當n == INT_MIN
時,不要使用a = -n
因為這是未定義的行為(UB),因為-n
會溢出int
數學。
使用a = n%10
將導致某個值 [-9... 0] 因為n < 0
。 在使用它打印數字之前不需要否定a
,只需減去。
int n = INT_MIN;
int a = n%10;
putchar('0' - a);
要打印整個int
,請注意負值[INT_MIN... -1]
正值[1... INT_MAX]
*1更多。 與其將負數否定為正數(並讓 UB 帶有INT_MIN
),不如將正數否定為負數。
#include <limits.h>
#include <stdio.h>
...
int n = {some value from INT_MIN to INT_MAX};
int a = n < 0 ? n : -n;
char buf[21];
char *p = buf + sizeof buf - 1;
*p = '\0';
do {
p--;
*p = '0' - a%10;
a /= 10;
} while (a);
if (n < 0) {
*--p = '-';
}
puts(p);
即使我們使用long long
或intmax_t
而不是int
,這種方法也有效。 我們只需要調整緩沖區長度。 char buf[21]
對於 64 位整數來說足夠大。
*1使用公共 2 的補碼 integer 編碼,總有一個負數。 對於罕見的 1 補碼和符號幅度編碼,可能會在 C2x 中被丟棄,但情況相同。 當然,這些可能有 +0和-0,但讓我們將其留給歷史編程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.