[英]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.