C++笔记-10-循环语句

while语句

语法:while(循环条件){循环语句}

只要循环条件为真就会执行循环语句,直到不为真时退出循环

cpp 复制代码
#include <iostream>
#include<iomanip>
using namespace std;

int main() {
	//在控制台打印0-9
	int i = 0;
	while (i < 10) {
		cout << i++ << endl;
	}
	return 0;
}

使用while时要注意循环条件,不要造成死循环

练习题:猜数字

cpp 复制代码
#include <iostream>
#include<iomanip>
#include<ctime>
using namespace std;

int main() {
	//添加随机数种子,使每次运行程序产生不同的随机数
	srand((unsigned int)time(NULL));
	int num = rand() % 100 + 1, val;
	while (1) {
		cout << "请输入你要猜的数字(1-100)" << endl;
		cin >> val;
		if (val > num) {
			cout << "你猜的数字大了" << endl;
		}
		else if (val < num) {
			cout << "你猜的数字小了" << endl;
		}
		else {
			cout << "恭喜你,猜对了" << endl;
			break;
		}
	}
	return 0;
}

do-while语句

语法:do{循环语句}while(循环条件)

与while的区别:do-while会先执行一次循环语句,再判断循环条件的真假执行下一次循环,while是先判断循环条件再决定是否执行循环语句.

cpp 复制代码
#include <iostream>
using namespace std;
int main() {
	int i = 0;
	do
	{
		cout << i++ << endl;
	} while (i < 10);
	return 0;
}

for循环语句

语法:for(起始表达式;条件表达式;末尾循环体) {循环语句;}

cpp 复制代码
#include <iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main() {
	for (int i = 0; i < 10; i++)
	{
		cout << i << endl;
	}
	return 0;
}
相关推荐
weiabc2 分钟前
今日C/C++学习笔记20260223
c语言·c++·学习
CoovallyAIHub4 分钟前
AAAI 2026 | 华中科大联合清华等提出Anomagic:跨模态提示零样本异常生成+万级AnomVerse数据集(附代码)
深度学习·算法·计算机视觉
悲伤小伞17 分钟前
9-MySQL_索引
linux·数据库·c++·mysql·centos
npupengsir18 分钟前
nano vllm代码详解
人工智能·算法·vllm
m0_5698814721 分钟前
C++中的组合模式高级应用
开发语言·c++·算法
m0_7301151126 分钟前
高性能计算负载均衡
开发语言·c++·算法
Hello_Embed32 分钟前
LVGL 入门(十五):接口优化
前端·笔记·stm32·单片机·嵌入式
灰色小旋风33 分钟前
力扣19删除链表的倒数第N个结点(C++)
c++·算法·leetcode·链表
孞㐑¥34 分钟前
算法—记忆化搜索
开发语言·c++·经验分享·笔记·算法
二进制星轨34 分钟前
leecode-70-颜色分类-算法题解
数据结构·算法·排序算法