상세 컨텐츠

본문 제목

Ternary if statement

c++

by Riella 2020. 7. 19. 00:45

본문

728x90

There is a short way to write if statement: ternary if statement.

The format is that (condition) ? [if true, here] : [if false, here]

When using in cout, make sure to use parenthesis like below code.

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
    string weather = "sunny";
    double humid = 0.7;
    weather = (humid > 0.5) ? "rainy" : "sunny";
    cout << "Today'\s weather is " << weather << endl;
    //this is the same thing
    cout << "Today'\s weather is " << ((humid > 0.5) ? "rainy" : "sunny");

    double e = 2.718;
    bool isOne = (round(log(e))) ? true : false;
    cout << "log(e) is approximatly one: " << isOne << endl;
    return 0;
}

관련글 더보기

댓글 영역