C语言 在 printf 中为正数打印前导“+”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3589242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print a leading '+' for positive numbers in printf
提问by user292844
I've a temperature conversion program as an assignment, which I've completed. The program has many printfstatements in it which print the temperature. Now the negative temperatures are printed the way I want them but the positive temperatures are printed without a leading +sign.
我有一个温度转换程序作为作业,我已经完成了。该程序中有许多printf打印温度的语句。现在负温度以我想要的方式打印,但正温度打印时没有前导+符号。
Now what is the best way to get printfprint a leading +sign for positive number. All I could think of is to change
现在printf打印+正数的前导符号的最佳方法是什么。我能想到的就是改变
printf("Min temp = %d\n",max_temp)
to
到
if(max_temp > 0)
printf("+");
printf("Min temp = %d\n",max_temp)
But that calls for many changes in program :(
但这需要对程序进行许多更改:(
Another option is to write my own print function and put this logic there. What do you suggest ?
另一种选择是编写我自己的打印函数并将此逻辑放在那里。你有什么建议?
回答by codaddict
回答by shreddd
Add the + flag. Here is an example.
添加 + 标志。这是一个例子。
int n;
printf("%+d", n);
(assuming n is an int - just replace %d for other numeric types)
(假设 n 是 int - 只需将 %d 替换为其他数字类型)

