【小白学习C++ 教程】四、C++逻辑运算符、While循环和For 循环
发布日期:2021-07-01 02:11:14 浏览次数:2 分类:技术文章

本文共 1512 字,大约阅读时间需要 5 分钟。

@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 
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" ; } }

While循环

在下面的示例中,只要变量 ( i) 小于 5 ,循环中的代码就会一遍又一遍地运行:

#include 
using namespace std;int main(){
int i = 0; while (i < 5) {
cout << i << "\n"; i++; }}

、

下面是一个程序,要求用户猜测1-10之间的数字,答案是8!

现在,与其只要求用户回答一次,添加一个while循环,让他们最多回答 50 次!

#include 
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"; } }

For 循环

打印 0 到 10 之间的偶数值:

#include 
using namespace std;int main(){
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n"; }}

转载地址:https://maoli.blog.csdn.net/article/details/117435546 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【小白学习C++ 教程】五、C++数据结构向量和数组
下一篇:【小白学习C++ 教程】三、C++用户输入、判断语句和switch

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月16日 09时23分26秒