C, C++/codecademy
조건문, 연산자
짱짱이_
2023. 2. 20. 23:56
<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;
}