C++基本中の基本その4

※自分用メモ
※引用元「ローベルのC++入門講座」

【条件分岐】
・条件分岐の書式は if(<条件>){ <実行文1> } else{ <実行文2> }
else 文はなくてもよい
・<条件>用の演算子がある

#include <iostream>
using namespace std;

void age()
{
    int x;
    
    cout << "How old are you?" << flush;
    cin >> x;
    
    if (13 <= x && x <= 19)
    {
        cout << "Oh, You're a teenager." << endl;
    }
    else
    {
        cout << "Oh, You're not a teenager" << endl;
    }
}

int main()
{
  age();
  age();
  
  return 0;
}

結果

How old are you? 75
Oh, You're not a teenager
How old are you? 19
Oh, You're a teenager.
#include <iostream>
using namespace std;

void age()
{
    int x;
    
    cout << "How old are you?" << flush;
    cin >> x;
    
    if (0 <= x && x <= 32)
    {
        cout << "Oh, You're younger than me." << endl;
    }
    if (x >= 34)
    {
        cout << "Oh, You're older than me" << endl;
    }
    if (x == 33)
    {
        cout << "Oh, we're the same age." << endl;
    }
}

int main()
{
  age();
  age();
  age();
  
  return 0;
}

結果

How old are you? 29
Oh, You're younger than me.
How old are you? 56
Oh, You're older than me
How old are you? 33
Oh, we're the same age.