C++ Note(Chapter5:Loop)

本文详细介绍了C++中的循环控制结构,包括`while`、`do-while`和`for`循环的用法及策略。通过案例研究如猜数字游戏和减法测试,阐述了如何设计和控制循环。此外,还讲解了使用哨兵值终止循环的概念以及`break`和`continue`语句在循环中的应用,最后讨论了何时选择不同类型的循环以及嵌套循环的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Chapter 5

5.1 The while Loop

while Loop 的语法:

while(loop-continuation-condition)
{
	//loop body
	Statements(s);
}

循环中包含重复执行的语句部分称为loop bodyloop body的一次执行称为循环的一次迭代,每个循环都包含一个loop-continuation-condition,其为boolean表达式,控制loop body的进行。loop-continuation-condition结果为Ture时,loop body继续执行,如果结果为false,循环结束,program执行while之后的语句。

int count = 0;
while(count < 100)             //loop-continuation-condition
{
	cout << "Welcome to C++\n"; //loop body
	count++;
}

在这个循环中,count作为计数控制循环变量来记录执行的次数,我们可以知道循环体应该执行多少次。

int sum = 0, i = 1;
while(i < 10)
{
    sum += i;
    i++;
}
cout << "Sum is " << sum;  //此程序用while循环计算了从0到10的累加和

如果这个程序将循环体内的i++删除,这个程序将会变为无限循环,因为condition永远为false。

5.1.1 Case Study: Guessing Numbers

一般来说,写程序前的算法思考比开始写程序更加重要。我们可以将这个问题实际操作一边,查看每一步我们需要做什么,一般就是算法思路,继续进行细节上的完善就能得到最终的程序源代码。
对于一个需要循环的程序,我们往往最开始可能不知道哪里需要循环,可以先将一般的形式写出来,再run程序查看哪一部分需要我们写循环,再加上即可。

* 1.生成随机数
* 2.提示用户第一次猜测数字
* 3.比较输入数字和随机数,在一个while循环中如果两者不等
*   提示用户输入数字与随机数的大小关系用户继续重新输入数字直到二者相等
* 4.告诉用户结果
*/

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main() 
{	//1.生成随机数,这次需要生成的为[0,100]。
	//要取得[a,b]的随机整数,使用(rand()%(b-a+1)+a);
	srand(time(0));
	int randomNumber = rand() % 101;

	//提示用户输入guess
	cout << "Please enter your guessd number: ";
	int userNumber;
	cin >> userNumber;

	//check用户guess和随机数
	while (userNumber != randomNumber) //如果用户guess不等于随机数,进入循环。
									   //否则即跳出循环
	{
		if (userNumber < randomNumber) 
		{
			cout << "Your guess is too lower, please enter your guess again: ";
			cin >> userNumber;
		}
		else if (userNumber > randomNumber) 
		{
			cout << "Your guess is too high, please enter your guess again: ";
			cin >> userNumber;
		}
	}

	cout << "The number is " << userNumber << endl;

	return 0;
}

5.1.2 Loop Design Strtegi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值