【小白学习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整除,那么它就是闰年
#includeint 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 ,循环中的代码就会一遍又一遍地运行:
#includeusing namespace std;int main(){ int i = 0; while (i < 5) { cout << i << "\n"; i++; }}
下面是一个程序,要求用户猜测1-10之间的数字,答案是8!
现在,与其只要求用户回答一次,添加一个while循环,让他们最多回答 50 次!
#includeint 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 之间的偶数值:
#includeusing namespace std;int main(){ for (int i = 0; i <= 10; i = i + 2) { cout << i << "\n"; }}
转载地址:https://maoli.blog.csdn.net/article/details/117435546 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2024年04月16日 09时23分26秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
how2heap-fastbin_dup_consolidate
2019-04-30
tf keras SimpleRNN源码解析
2019-04-30
MyBatisPlus简单入门(SpringBoot)
2019-04-30
攻防世界web进阶区web2详解
2019-04-30
xss-labs详解(上)1-10
2019-04-30
xss-labs详解(下)11-20
2019-04-30
攻防世界web进阶区ics-04详解
2019-04-30
sql注入总结学习
2019-04-30
Python 之 histogram直方图
2019-04-30
Python实现决策树 Desision Tree & 可视化
2019-04-30
决策树 Decision tree
2019-04-30
MATLAB与CUDA
2019-04-30
Linux png转jpg (convert命令)
2019-04-30
Ubuntu更新后终端中字体的颜色全是白色
2019-04-30
vscode git
2019-04-30
基于MATLAB的二进制数字调制与解调信号的仿真——2PSK
2019-04-30
基于MATLAB的模拟调制信号与解调的仿真——DSB
2019-04-30
HDU - 1166 敌兵布阵 (树状数组模板题/线段树模板题)
2019-04-30
CodeForces - 456C Boredom (dp)
2019-04-30