프로그래밍/C, C++

조건문, 연산자

jjjjjjyun 2025. 5. 5. 16:45

<if문>

if (조건)

{    ~~~ ; } 형태

 

조건이 참이면 { } 안이 실행되고 아니면 넘어간다.

 

 

 

 

 

<관계 연산자>

관계 연산자 종류

 

 

 

<if, else문>

 

 

 

조건이 참이면 if문의 do something 부분이 실행하고 아니면 else문 실행한다.

 

 

 

 

 

<if, else if, else문>

조건이 3개 이상일 때 이용한다.

 

 

 

 

 

<switch문>

조건이 정수 형식일 때 이용된다. 각각의 case 마지막 부분에 break를 추가해준다.

 

 

 

 

 

예제) 몸무게 계산하기

#include <iostream>
int main() {
  std::cout << "Enter the current earth weight.\n";
  double weight;
  std::cin >> weight;
  std::cout << "Choose the planet\n";
  std::cout << "1. Mercury  2. Venus  3. Mars\n";
  std::cout << "4. Jupiter  5. Saturn  6. Uranus  7. Neptune\n";
  int x;
  std::cin >> x;
  
  switch(x){
    case 1:
      weight *= 0.78;
      break;
    case 2:
      weight *= 0.39;
      break;
    case 3:
      weight *= 2.65;
      break;
    case 4:
      weight *= 1.17;
      break;
    case 5:
      weight *= 1.05;
      break;
    case 6:
      weight *= 1.23;
      break;
  }
  std::cout << "Your weight:  "<<weight <<std::endl;
  }

 

'프로그래밍 > C, C++' 카테고리의 다른 글

vector  (0) 2025.05.05
에러  (0) 2025.05.05
논리 연산자, 루프(for, while)  (0) 2025.05.05
포인터  (0) 2025.03.15
컴파일과 실행  (0) 2025.03.15