C++ 基础模板
#include <iostream>
using namespace std;
int main(){
cout<<"Hello World!"<<endl;
system("pause");
return 0;
}
变量存在的意义:
方便我们管理内存空间;给变量分配合适的内存空间
变量创建的语法:
数据类型 变量名 = 变量初始值
- int a = 0;
常量的定义方式:
- #define 宏常量
- const 修饰的变量
关键字(即:标识符)
变量名要见名知意:
num1 = 1;
num2 = 2;
sum = num1 + num2;
cout<<sum<<endl;
整型(4种数据类型):
short, int, long, long long
int 占用4个字节,那么可以表示的数字范围是:
4 * 8 = 32 位
2 ** 32 = 4294967296
除以 2 (一半):
2147483648
所以范围是:
-2147483648 到 2147483647
可以利用 sizeof 求出数据类型占用内存大小
语法: sizeof(数据类型/变量)
实型(浮点型)
作用:用于表示小数
- 单精度 float (占用空间:4字节, 7位有效数字)
- 双精度 double (占用空间:8字节,15到16位有效数字)
比如:3.14 (一个3个有效数字)
- 默认情况下,输出一个小数,会显示 6 位有效数字
- 在C++中,cout默认精度是6位。需要设置精度才能输出你想要的位数。
- 所以需要指定精度,如果习惯使用c的输出,可以在printf中使用%lf输出。
cout << setprecision(n) << i<< endl;
#include <iostream>
#include <iomanip>
using namespace std;
# define Day 7
int main(){
cout<<"Hello World!"<<endl;
int a = 10;
cout<<"a = "<< a <<endl;
cout<<"一周有 "<< Day << " 天" <<endl;
const int month = 12;
cout<<"一年有 "<<month<<" 个月份"<<endl;
// 整型占用空间
short num01 = 01;
int num11 = 11;
long num21 = 21;
long long num22 = 22;
cout<<"short类型占用的内存空间是 "<<sizeof(num01)<<" 个字节" <<endl;
cout<<"int类型占用的内存空间是 "<<sizeof(int)<<" 个字节" <<endl;
cout<<"long类型占用的内存空间是 "<<sizeof(long)<<" 个字节" <<endl;
cout<<"long long类型占用的内存空间是 "<<sizeof(num22)<<" 个字节" <<endl;
// 实型
float f1 = 3.1415926535f;
cout<<"f1 ="<<f1<<endl;
cout<<sizeof(f1)<<endl;
cout<<setprecision(11)<<f1<<endl;
double f2 = 3.1415926535;
cout<<"f2 ="<<f2<<endl;
cout<<sizeof(f2)<<endl;
// 科学计数法
float f3 = 3e2; // 3 * 10^2
cout<<setprecision(6)<<"f3 = "<<f3<<endl;
float f4 = 3e-2; // 3 * 0.1^2
cout<<"f4 = "<<f4<<endl;
// printf
double f5 = 3.1415926535;
printf("f5 = %.10lf\n", f5);
system("pause");
return 0;
}
运行结果:
Hello World!
a = 10
一周有 7 天
一年有 12 个月份
short类型占用的内存空间是 2 个字节
int类型占用的内存空间是 4 个字节
long类型占用的内存空间是 4 个字节
long long类型占用的内存空间是 8 个字节
f1 =3.14159
4
3.141592741
f2 =3.1415926535
8
f3 = 300
f4 = 0.03
f5 = 3.1415926535
请按任意键继续. . .