黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难

C++笔记
1. 1书写hello,world
#include <iostream>
using namespace std;
int main()
{
cout<<”hello,world”<< endl;
system(“pause”);
return 0;
}
1.2注释
//或/* */
1.3常量的定义
#define 常量名 常量值
#define day 7
cout<<”一周共有”<<day<<”天”<< endl;
const 数据类型 常量名 = 常量值;
const int month = 12;
cout<<”一年有”<<month<<”个月”<< endl;
2.1 sizeof
cout<<sizeof(int)<< endl;
2.2浮点型(实型)
单精度 float (7位)
float f1 = 3.14f;//(不加f默认为双精度)
精度 double(15-16位)
double d1 = 3.14
科学计数法
float f2 = 3e2;//3*10’2=300
2.3字符串
1.C风格
char str[] = “hello,world”;
cout << str << endl;
2.C++风格
string str2 = “hello,world”;
cout << str2 << endl;
2.4布尔类型 bool
bool flag = true;
cout<< flag << endl;
2.5数据的输入
int a;
cin >> a;
cout<< a << endl;
3.1三目运算符
c=(a>b?a:b); //如果a>b,则c=a,否则c=b
(a> b?a:b)=100;//赋值
3.2 switch语句
缺点:判断的只能是整型或字符型,不可以是区间
优点:效率高
switch(表达式)
{
case 1:
语句1;
break;//退出分支
……
default:
语句;
}
3.3 rand函数
#include<ctime>//time系统时间头文件
srand((unsigned int)time(NULL));
//添加随机数种子,利用系统时间生成随机数,避免生成随机数一样。
rand ( ) % 100+1; //生成0~100的随机数
4.1一维数组
1.数据类型 数组名[ 数组长度 ];
int arry [ 5 ];
//数组下标从0开始
2.数据类型 数组名[数组长度]={值1,…… };
int arry [ 5 ]={10,20,……};
//如果初始化数据时没有全部填写,剩余用0补齐
3. 数据类型 数组名[ ] = {值1,…… };
4.2数组名用途
1.
2.
4.3数组内元素逆置
int arr[5]={1,3,2,5,4};
int start=0;
int end=sizeof(arr)/sizeof(arr[0])-1;
while(start<end)
{
int temp=arry[start];
arry[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
for(i=0;i<5;i++)
{
cout<<arr[i]<<endl;
}
4.4冒泡排序
int arr[9]={4,2,8,0,5,7,1,3,9};
int i,j; //i—排序次数,j—对比次数
//总排序次数为元素个数-1
for(i=0;i<9-1;i++)
{
//内层对比次数=元素个数-循环次数-1
for(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(i=0;i<9;i++)
{
cout<<arr[i]<<" ";
}