
@Author:Runsen
逻辑运算符用于组合两个或多个条件。它们允许程序做出更灵活的决策。逻辑运算符的运算结果是或的bool值。true和false
我们将介绍三个逻辑运算符:

Operator | Example |
|---|---|
&& | x < 5 && x < 10 |
|| | x < 5 || x < 4 |
! | !(x < 5 && x < 10) |
编写一个jump_year.cpp程序,该程序:
识别年份必须考虑3个标准:
#include <iostream>
int main() {
int y = 0;
std::cout << "Enter year: ";
std::cin >> y;
if (y < 1000 || y > 9999) {
std::cout << "Invalid entry.\n";
}
else if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
std::cout << y;
std::cout << " falls on a leap year.\n";
}
else {
std::cout << y << " is not a leap year.\n" ;
}
}
在下面的示例中,只要变量 ( i) 小于 5 ,循环中的代码就会一遍又一遍地运行:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i < 5)
{
cout << i << "\n";
i++;
}
}

、
下面是一个程序,要求用户猜测1-10之间的数字,答案是8!
现在,与其只要求用户回答一次,添加一个while循环,让他们最多回答 50 次!
#include <iostream>
int main() {
int guess;
int tries = 0;
std::cout << "I have a number 1-10.\n";
std::cout << "Please guess it: ";
std::cin >> guess;
// Write a while loop here:
while (guess != 8 && tries < 50) {
std::cout << "Wrong guess, try again: ";
std::cin >> guess;
tries++;
}
if (guess == 8) {
std::cout << "You got it!\n";
}
}

打印 0 到 10 之间的偶数值:
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i <= 10; i = i + 2)
{
cout << i << "\n";
}
}