C++ 基础语法
C++ 基础语法

C++ 基础语法

一、初识 C++

1、第一个 C++ 程序

#include <iostream>

using namespace std;

int main() {
  cout<<"hello world"<<endl;
  return 0;
}

2、代码注释

解释代码的意思

#include <iostream>

using namespace std;
/*
----- 多行注释
*/
int main() {
  // 输出hello world  ------单行注释
  cout<<"hello world"<<endl;
  return 0;
}

3、变量

可修改的参数

#include <iostream>
using namespace std;

int main() {
  // 数据类型 变量名 = 变量的初始值;
  int a = 10;
  float b = 10.1;
  double c = 10.2;
  return 0;
}

4、常量

不可修改的参数

#include <iostream>
// 方法一
#define day 7

using namespace std;

int main() {
  // 方法二
  const int a = 7;
  return 0;
}

5、命名规则

数字不能作为变量名第一个字符

#include <iostream>

using namespace std;

int main() {
  int _i = 0;
  int i_ = 0;
  int 2i = 0;// 这个是错误命名
}

二、数据类型

1、整型

C++ 中表示整型有以下几种方式

数据类型占用空间取值范围
short2 字节(-2^15 ~ 2^15-1)
int4 字节(-2^31 ~ 2^31-1)
long8 字节(linux) / 4字节(windows)(-2^31 ~ 2^31-1)
long long8 字节(-2^63 ~ 2^63-1)
#include <iostream>

using namespace std;

int main() {
  short num = 32768;
  int num1  = 32768;
  cout<< num << endl;  // 输出结果-32768
  cout<< num1 << endl; // 输出结果32768
  return 0;
}

2、sizeof 关键字

利用sizeof 求数据类型占用内存大小

#include <iostream>

using namespace std;

int main() {
  short num = 10;
  cout << sizeof(num) << endl; //输出结果 2
  return 0;
}

3、浮点型

数据类型占用空间有效数字范围
float4 字节7 位有效数字
double8 字节15 ~ 16位有效数字

编译器默认为双精度, 默认输出后六位

float f1 = 3.14f;
#include <iostream>

using namespace std;

int main() {
  float f1 = 3.14f;
  double d1 = 3.1415926;
  cout << f1 << endl; // 输出结果 3.14
  cout << d1 << endl; // 输出结果 3.141592
  float f2 = 3e2;
  float f3 = 3e-2;
  cout << f2 << endl; // 输出结果 300
  cout << f3 << endl; // 输出结果 0.03
  return 0;
}

4、 字符型

显示单个字符
仅仅占用 1 个字节
ASCLL编码放入存储单元

#include <iostream>
 
using namespace std;

int main() {
  char ch = 'a';
  cout << ch << endl; // 输出结果 a
  cout << (int)ch << endl; // 输出结果 98
  char 
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注