[英]Conditional inside `printf` statement
Is there a way to shorten this: 有没有一种方法可以缩短此时间:
if (a > 0)
printf("%d", a);
else
printf("%d", -a);
I mean, is there a way to write all this inside one printf
with the ?
我的意思是,有没有写全这里面一个方式
printf
用?
operator? 操作员?
This should work for you: 这应该为您工作:
printf("%d", (a > 0? a: -a));
Input/Output: 输入输出:
5 -> 5
-5 -> 5
A little test program: 一些测试程序:
#include<stdio.h>
int main() {
int a = -5, b = 5;
printf("%d\n", (a > 0? a: -a));
printf("%d\n", (b > 0? b: -b));
return 0;
}
Use the ternary operator. 使用三元运算符。
printf("%d\n",(a>0) ? a:-a);
If the condition is true
, then after the ?
如果条件为
true
,那么之后?
will be executed. 将被执行。 Otherwise, after the
:
will be executed. 否则,在
:
将被执行。
It looks that you want to obtain an absolute value . 看来您想获得一个绝对值 。 For
int
type you might use abs()
function from <stdlib.h>
header for such purpose: 对于
int
类型,您可以使用<stdlib.h>
标头中的abs()
函数来实现此目的:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a;
a = 3;
printf("%d\n", abs(a));
a = -3;
printf("%d\n", abs(a));
return 0;
}
There are also labs()
for llabs()
(C99) for long int
and long long int
types respectively as well as for floating-point types eg fabs()
from <math.h>
. 还有针对
long int
和long long int
类型以及浮点类型(例如<math.h>
fabs()
labs()
的llabs()
(C99)的labs()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.