C++学习笔记02,C++基础

1、//猜数小游戏

#include <ctime>	//包含time系统时间头文件

int main13()
{
	//添加随机数种子,利用当前系统时间生成随机数,防止每次随机数都相同
	srand((unsigned int)time(NULL));//time需要头文件
	//系统产生一个1~100的随机数
	int magic = rand() % 100 + 1;	//rand() % 100生成0~99的随机数

	while (1)
	{
		//玩家猜测
		int guess = 0;
		cout << "请输入你猜的数:";
		cin >> guess;
		//判断猜测
		if (guess > magic)
		{
			cout << "错误,猜的数太大了!";
		}
		else if (guess < magic)
		{
			cout << "错误,猜的数太小了!";
		}
		else
		{
			cout << "恭喜你猜对了!";
			break;
		}
	}

	system("pause");
	return 0;
}

2、//简单的数组逆置

int main14()
{
	int arr[5] = { 10,20,30,40,50 };	//arr就是数组首地址
	cout << "数组逆置前:" << endl;
	for (int i = 0;i < 5;i++)
	{
		cout << arr[i] << "\t";
	}
	cout << endl;

	int first = 0;	//首下标
	int tail = sizeof(arr)/sizeof(arr[0]) - 1;	//尾下标
	int temp;	//临时变量

	while (first < tail)
	{
		//元素互换
		temp = arr[first];
		arr[first] = arr[tail];
		arr[tail] = temp;
		//更新下标
		first++;
		tail--;
	}
	
	cout << "逆置后的数组是:" << endl;
	for (int i = 0;i < 5;i++)
	{
		cout << arr[i] << "\t";
	}
	cout << endl;

	return 0;
}

3、//冒泡排序

int main15()
{
	int arr[9] = { 90,80,70,60,50,40,30,20,10 };
	cout << "冒泡排序前:" << endl;
	for (int i = 0;i < 9;i++)
	{
		cout << arr[i] << "\t";
	}
	cout << endl;
	
	int max = 0;
	int temp = 0;
	for (int j = 0;j < (9 - 1);j++)
	{
		for (int i = 0;i < 8-j;i++)
		{
			if (arr[i] > arr[i+1])
			{
				//元素交换
				temp = arr[i];
				arr[i] = arr[i + 1];
				arr[i + 1] = temp;
			}
		}
	}
	
	cout << "冒泡排序后的数组是:" << endl;
	for (int i = 0;i < 9;i++)
	{
		cout << arr[i] << "\t";
	}
	cout << endl;

	system("pause");
	return 0;
}

(哔哩哔 哩黑马程序员 C++教程 学习笔记,如有侵权请联系删除)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值