IT 프로그래밍/C++
[따배시 2.6] 불리언 연산자와 조건문 if
기술1
2024. 3. 7. 19:47
int main()
{
using namespace std;
bool b1 = true;
bool b2(false);
bool b3{ true };
b3 = false;
if (false)
cout << "This is true" << endl;
return 0;
}
bool 을 통해 true, false를 판별할 수 있습니다. 앞에 bool b1 = true;를 해주면 bool연산자를 통해서 and or not 등을 표현할 수 있습니다. 프로그래밍의 제어 흐름을 조정하거나 조건을 검사할 때 사용합니다.
#include <iostream>
int main()
{
using namespace std;
if (5)
{
cout << "True" << endl;
}
else
cout << "False" << endl;
return 0;
}
여기서 출력값이 true 가 나오는 이유는 if는 0이 아니면 다 true를 반환하기 때문입니다.
그럼 if에 0을 넣어준다면 false가 나오겠죠? 0 이 아닌 숫자는 다 true를 반환합니다.
#include <iostream>
int main()
{
using namespace std;
bool b;
cin >> b;
cout << std::boolalpha;
cout << "Your input : " << b << endl;
return 0;
}
0이 아니면 true가 나오는 것을 볼 수 있습니다.
정수 하나를 입력받고 그 숫자가 홀수인지 짝수인지 출력하는 프로그램
#include <iostream>
int main()
{
using namespace std;
int a = 0;
cin >> a;
if (a / 2 == 0)
cout << "This number is even" << endl;
else
cout << "This number is odd" << endl;
return 0;
}
간단하게 마지막 예제를 만들어봤습니다.