【小白学习C++ 教程】四、C++逻辑运算符、While循环和For 循环
【摘要】 @Author:Runsen
文章目录
逻辑运算符While循环For 循环
逻辑运算符
逻辑运算符用于组合两个或多个条件。它们允许程序做出更灵活的决策。逻辑运算符的运算结果是或的bool值。true和false
我们将介绍三个逻辑运算符:
&&:and逻辑运算符||:or逻辑运算符!:not逻辑运算符
OperatorExa...
@Author:Runsen
逻辑运算符
逻辑运算符用于组合两个或多个条件。它们允许程序做出更灵活的决策。逻辑运算符的运算结果是或的bool值。true和false
我们将介绍三个逻辑运算符:
- &&:and逻辑运算符
- ||:or逻辑运算符
- !:not逻辑运算符
Operator | Example |
---|---|
&& | x < 5 && x < 10 |
|| |
x < 5 || x < 4 |
! | !(x < 5 && x < 10) |
编写一个jump_year.cpp程序,该程序:
- 需要一年作为输入。
- 检查年份是否为四位数。
- 显示年份是否属于闰年。
识别年份必须考虑3个标准:
- 如果年份可以被 4 整除,那么它就是闰年,但是……
- 如果那一年能被100整除,而不能被400整除,那么就不是闰年。
- 如果该年可以被400整除,那么它就是闰年
#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" ; }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
While循环
在下面的示例中,只要变量 ( i) 小于 5 ,循环中的代码就会一遍又一遍地运行:
#include <iostream>
using namespace std;
int main()
{ int i = 0; while (i < 5) { cout << i << "\n"; i++; }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
下面是一个程序,要求用户猜测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";
} }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
For 循环
打印 0 到 10 之间的偶数值:
#include <iostream>
using namespace std;
int main()
{ for (int i = 0; i <= 10; i = i + 2) { cout << i << "\n"; }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
文章来源: maoli.blog.csdn.net,作者:刘润森!,版权归原作者所有,如需转载,请联系作者。
原文链接:maoli.blog.csdn.net/article/details/117435546
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)