C++ if else 条件语句的使用方法
if()
{
}
else if ()
{
}
普通的if(条件1 || 条件二)中如果条件1满足的话就不会再判断条件二是否满足了,而是直接执行if后面的语句了
实例if
#include
using namespace std;
int main() {
int a, b, c;
a = 2;
b = 3;
if(a < b)
cout << "a is less than bn";
if(a == b)
cout << "you won't see thisn";
cout << "n";
c = a - b;
cout << "c contains -1n";
if(c >= 0)
cout << "c is non-negativen";
if(c < 0)
cout << "c is negativen";
cout << "n";
c = b - a; // c now contains 1
cout << "c contains 1n";
if(c >= 0)
cout << "c is non-negativen";
if(c < 0)
cout << "c is negativen";
return 0;
}当然我们还有if else
实例
#include
int main()
{
int firstNumber, secondNumber;
std::cout << "Please enter a big number: ";
std::cin >> firstNumber;
std::cout << "nPlease enter a smaller number: ";
std::cin >> secondNumber;
if (firstNumber > secondNumber)
std::cout << "nThanks!n";
else
std::cout << "nOops教程. The second is bigger!";
return 0;
}多重
#include
int main()
{
int firstNumber =2;
int secondNumber = 3;
if (firstNumber >= secondNumber)
{
if ( (firstNumber secondNumber) == 0) // evenly divisible?
{
if (firstNumber == secondNumber)
std::cout << "They are the same!n";
else
std::cout << "They are evenly divisible!n";
}
else
std::cout << "They are not evenly divisible!n";
}
else
std::cout << "Hey! The second one is larger!n";
return 0;
}
Hey! The second one is larger!
if else if实例#include
using namespace std;
int main()
{
int x;
for(x=0; x<6; x++) {
if(x==1) cout << "x is onen";
else if(x==2) cout << "x is twon";
else if(x==3) cout << "x is threen";
else if(x==4) cout << "x is fourn";
else cout << "x is not between 1 and 4n";
}
return 0;
}