#include<iostream>intmain(){std::cout<<"Enter an integer: ";intx{};std::cin>>x;if(x==0)std::cout<<"The value is zero\n";if(x!=0)std::cout<<"The value is non-zero\n";return0;}
或者这样:
1 2 3 4 5 6 7 8 910111213141516
#include<iostream>intmain(){std::cout<<"Enter an integer: ";intx{};std::cin>>x;boolzero{(x==0)};if(zero)std::cout<<"The value is zero\n";if(!zero)std::cout<<"The value is non-zero\n";return0;}
这两个程序其实没必要这么复杂,我们可以使用另一种形式的 if 语句——if-else语句。if-else语句的形式如下:
1234
if (condition)
true_statement;
else
false_statement;
#include<iostream>intmain(){std::cout<<"Enter an integer: ";intx{};std::cin>>x;if(x==0)std::cout<<"The value is zero\n";elsestd::cout<<"The value is non-zero\n";return0;}
现在,程序的输出结果如下:
12
Enter an integer: 0
The value is zero
12
Enter an integer: 5
The value is non-zero
链式 if 语句
有时候我们需要连续检查一些条件是否为真。我们可以使用链式的if语句来完成,例如:
1 2 3 4 5 6 7 8 91011121314151617
#include<iostream>intmain(){std::cout<<"Enter an integer: ";intx{};std::cin>>x;if(x>0)std::cout<<"The value is positive\n";elseif(x<0)std::cout<<"The value is negative\n";elsestd::cout<<"The value is zero\n";return0;}
#include<iostream>// 如果 x 和 y 相等则返回 true 否则返回 falseboolisEqual(intx,inty){return(x==y);// 如果 x 和 y 相等,operator== 则返回 true 否则返回 false}intmain(){std::cout<<"Enter an integer: ";intx{};std::cin>>x;std::cout<<"Enter another integer: ";inty{};std::cin>>y;std::cout<<std::boolalpha;// print bools as true or falsestd::cout<<x<<" and "<<y<<" are equal? ";std::cout<<isEqual(x,y);// will return true or falsereturn0;}
我们可以使用 if 语句对上面的代码进行改写:
1 2 3 4 5 6 7 8 910111213141516171819202122232425
#include<iostream>// returns true if x and y are equal, false otherwiseboolisEqual(intx,inty){return(x==y);// operator== returns true if x equals y, and false otherwise}intmain(){std::cout<<"Enter an integer: ";intx{};std::cin>>x;std::cout<<"Enter another integer: ";inty{};std::cin>>y;if(isEqual(x,y))std::cout<<x<<" and "<<y<<" are equal\n";elsestd::cout<<x<<" and "<<y<<" are not equal\n";return0;}
两次运行上述程序:
123
Enter an integer: 5
Enter another integer: 5
5 and 5 are equal
123
Enter an integer: 6
Enter another integer: 4
6 and 4 are not equal