C++学习(黑马程序员课程)

本文介绍了C++中的基本概念,包括常量的使用、三目运算符和switch语句的逻辑控制,以及猜数字游戏中如何生成随机数。此外,还讨论了goto语句的使用和冒泡排序算法,展示了指针操作和二维数组的应用,并提到了空指针、野指针和常量指针的概念。
摘要由CSDN通过智能技术生成

黑马C++

C++常量

在这里插入图片描述

三目运算符

在这里插入图片描述

switch语句

在这里插入图片描述

猜数字游戏

在这里插入图片描述
添加随机数种子 利用当前系统时间生成随机数,防止每次输出随机数一样
srand((unsigned int)time(NULL));
系统生成随机数0~100
a = rand() % 100 + 1;

#include<iostream>
#include<stdlib.h>
#include<ctime>
using namespace std;
int main()
{
	int a,b;
	//添加随机数种子 利用当前系统时间生成随机数,防止每次输出随机数一样
	srand((unsigned int)time(NULL));
	//系统生成随机数0~100
	a = rand() % 100 + 1;

	while (cin >> b)
	{
		if (b == a)
		{
			cout << "right!" << endl;
			break;
		}
		else if (b > a)
			cout << "大了" << endl;
		else
			cout << "小了" << endl;
	}
	return 0;
}

在这里插入图片描述

goto语句

在这里插入图片描述

#include<iostream>
using namespace std;
int main()
{
	//goto语句
	cout << "1.xxxx" << endl;
	cout << "2.xxxx" << endl;

	goto FLAG;
	cout << "3.xxxx" << endl;
	cout << "4.xxxx" << endl;

	FLAG:
	cout << "5.xxxx" << endl;
	return 0;
}

在这里插入图片描述
goto语句不建议使用

冒泡排序

#include<iostream>
using namespace std;
int main()
{
	int arr[9] = { 4,2,8,0,5,7,1,3,9 };

	//总排序轮数为:元素个数-1
	for (int i = 0; i < 9 - i; i++)
	{
		//内层循环对比:次数=元素个数-当前轮数-1
		for (int j = 0; j < 9 - i - 1; j++)
		{
			//如果第一个数字比第二个数字大,交换两个数字
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	for (int i = 0; i < 9; i++)
		cout << arr[i] << endl;
	return 0;
}
//指针+冒泡排序
#include<iostream>
using namespace std;

void bubblesort(int* arr, int len)
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

void printarr(int* arr, int len)
{
	for (int i = 0; i < len; i++)
		cout << arr[i] << " ";
}
int main()
{
	int arr[10] = { 4,3,6,9,1,2,10,8,7,5};
	int len = sizeof(arr) / sizeof(arr[0]);
	bubblesort(arr, len);
	printarr(arr, len);
	return 0;
}

二维数组用途

在这里插入图片描述

C++分文件编写

在这里插入图片描述

指针

#include<iostream>
using namespace std;

int main()
{
	int a = 10;
	int* p;
	p = &a;
	cout <<"变量a地址为:" << p << endl;;
	
	//指针前加 * 代表解引用,找到指针指向的内存中数据
	*p = 1000;
	cout<<"变量a值为:" << a << endl;
	return 0;
}

在这里插入图片描述

空指针和野指针

在这里插入图片描述
野指针:指针指向非法地址空间
空指针和野指针都不是我们自己设定的地址,不能访问

常量指针

const int * p = &a;
特点:指针的指向可以修改,但指针指向的值不可以改

*p=20错误!!!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值