简体   繁体   中英

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 ? 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 ? 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:

#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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM