[英]How to print a positive number as a negative number via printf
在閱讀有關printf()時,我發現它可以通過以下代碼(for - )按照用戶的需要打印數字為正數或負數。但代碼不起作用且輸出為正值。請提及錯誤的位置。謝謝
#include<stdio.h>
int main()
{
printf (" %-d\n", 1977);
return 0;
}
從您的評論中看起來您誤讀了此頁面 。 -
和+
說明符做了兩件完全不同的事情,你認為' - '也不應該這樣做。
正如其他人所指出的那樣, -
確實沒有理由。 +
說明符打印帶有前導加號的正數(負數仍然得到前導減號):
printf("%d %d %+d %+d\n", -10, 10, -10, 10);
輸出:
-10 10 -10 +10
%-d
將調整整數字段,它不會翻轉符號。 改為:
printf (" %d\n", -1977);
這是在旗幟字符下的 print(3)
的完整摘錄:
- The converted value is to be left adjusted on the field bound‐ ary. (The default is right justification.) Except for n con‐ versions, the converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A - over‐ rides a 0 if both are given.
我現在看到你的真實問題:要使用適當的符號前置輸出,請使用+
flag字符明確顯示符號。 這里是提取物:
+ A sign (+ or -) should always be placed before a number produced by a signed conversion. By default a sign is used only for neg‐ ative numbers. A + overrides a space if both are used.
並使用它(命令行printf
大致相同):
matt@stanley:~/cpfs$ printf "%+d\n" 3 +3 matt@stanley:~/cpfs$ printf "%+d\n" -3 -3 matt@stanley:~/cpfs$ printf "%+u\n" -3 18446744073709551613
請注意,明確請求符號並不意味着將上述%u
示例中的相應整數視為已簽名。
printf (" -%d\\n", 1977);
將輸出-1997
(做壞事的方法),如果你想讓負數變為正數,請執行printf (" %d\\n", -1 * 1977);
(這樣做的好方法)
閱讀參考資料 ,了解格式說明符的工作原理
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.