#include<iostream>intmain(){std::cout<<"Enter a number: ";intx{};std::cin>>x;if(x>10)std::cout<<x<<" is greater than 10\n";elsestd::cout<<x<<" is not greater than 10\n";return0;}
程序输出结果如你所期望的那样:
12345
Enter a number: 15
15 is greater than 10
Enter a number: 4
4 is not greater than 10
多个条件语句
新手程序员可能会编写这样的程序:
1 2 3 4 5 6 7 8 910111213141516
#include<iostream>intmain(){std::cout<<"Enter your height (in cm): ";intx{};std::cin>>x;if(x>140)std::cout<<"You are tall enough to ride.\n";elsestd::cout<<"You are not tall enough to ride.\n";std::cout<<"Too bad!\n";// focus on this linereturn0;}
不过,程序的运行结果可能并不如愿:
123
Enter your height (in cm): 180
You are tall enough to ride.
Too bad!
#include<iostream>intmain(){std::cout<<"Enter your height (in cm): ";intx{};std::cin>>x;if(x>140)std::cout<<"You are tall enough to ride.\n";elsestd::cout<<"You are not tall enough to ride.\n";std::cout<<"Too bad!\n";// focus on this linereturn0;}
这也就看到很清楚了,显然 “Too bad!” 在任何情况下都会被打印。
但是,通常希望基于某些条件执行多个语句。为此,我们可以使用复合语句(块):
1 2 3 4 5 6 7 8 9101112131415161718
#include<iostream>intmain(){std::cout<<"Enter your height (in cm): ";intx{};std::cin>>x;if(x>140)std::cout<<"You are tall enough to ride.\n";else{// note addition of block herestd::cout<<"You are not tall enough to ride.\n";std::cout<<"Too bad!\n";}return0;}
记住,block被当作一个单独的语句,所以现在工作正常:
12
Enter your height (in cm): 180
You are tall enough to ride.
123
Enter your height (in cm): 130
You are not tall enough to ride.
Too bad!
应该将单独的条件语句写作语句块吗?
对于 if 或 else 后面的单个语句是否应该显式地包含在语句块中,在程序员社区中引发了广泛的争论。
这样做通常有两个理由。首先,考虑下面的代码片段:记住,块被视为一个单独的语句,所以现在工作正常:
12
if(age>=21)purchaseBeer();
然后,如果你特别匆忙地将某个新功能加入到程序中:
123
if(age>=21)purchaseBeer();gamble();// will always execute