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错误!!!!!