C++ 基本语法

本文最后更新于:2022年4月22日 上午

C++ 基本语法

基本模板

#include <iostream>;
using namespace std;

int main () {
  
  // ... 测试代码
  
  system("pause");
  return 0;
}

整形

类型 占用空间
short (短整性) 2字节
int (整形) 4 字节
long (长整形) Linux 32位4字节, 64 位 8字节, 8 字节 window 4 字节
long long (长长整形) 8字节

实型(小数)

类型 占用空间
float(浮点型) 4 字节 后面跟上 f float num1 = 1.88f;
double 8字节 double num2 = 1.88;
// float 4字节,double 8字节
float num1 = 1.88f;
double num2 = 1.88;

cout << "float所占字节" << sizeof(num1) << endl;
cout << "double所占字节" << sizeof(num2) << endl;

输出

float所占字节4
double所占字节8

字符型

char 1字节

只能有一个字符,占 1 字节,如果有多个字符串,则只取最后一位

char chars1 = 'a';
char chars2 = 'abcd';
cout << "char 所占字节" << sizeof(chars1) << endl;
cout << "字符 chars1:" << chars1 << endl << endl;
cout << "char 所占字节" << sizeof(chars2) << endl;
cout << "字符 chars2:" << chars2 << endl;

输出

char 所占字节1
字符 chars1:a

char 所占字节1
字符 chars2:d

字符串

string 关键字

// C++ 风格型字符串
string s1 = "hello world";

// C 语言风格字符串 char 数组
char s2[] = "hello world";
cout << "字符串 s1:" << s1 << endl;
cout << "字符串 s2:" << s2 << endl;

输出

字符串 s1:hello world
字符串 s2:hello world

布尔类型

类型 占用空间
bool 1 字节 true:1,false:0
bool b1 = true;
bool b2 = false;

cout << "bool 所占字节:" << sizeof(b1) << endl;
cout << "布尔值 b1:" << b1 << endl;
cout << "布尔值 b2:" << b2 << endl;

输出

bool 所占字节:1
布尔值 b1:1
布尔值 b2:0

sizeof 关键字

通过 sizeof关键字可以查看所占内存的大小

cout << sizeof(int) << endl;  // 4

char a = 'a';
cout << sizeof(a) << endl;    // 1

输入

cin 来进行终端输入

string name;
cin >> name;

算术运算符 & 赋值运算符 & 比较运算符 & 逻辑运算符

基本常见的运算符都包含

+ - x / % 
++
-- 
+=
-=
*=
/=
>
<
==
!=
||
&&
~

条件判断

包含基本的

if

else

嵌套 if (案例 求三位同学最高分)

三目运算

循环语句

switch

while

do..while (案例 1000以内水仙花数)

for (案例 打印 7的倍数,能被7整除,包含7的数)

嵌套循环 (打印乘法表)

break;

cnotinue;

goto: 跳转

案例一 (案例 1000以内水仙花数)

1000 以内的水仙花数 如: 1^3 + 5^3+ 3^3 = 153。

int num3 = 99;

while (++num3 < 1000) {
  int hundred= (int)num3 / 100;
  int ten = (int)num3 % 100 / 10;
  int unit = num3 % 10;

  if (unit * unit * unit + ten * ten * ten + hundred * hundred * hundred == num3) {
    cout << "水仙花数:" << num3 << endl;
  }
}

输出

水仙花数:153
水仙花数:370
水仙花数:371
水仙花数:407

案例二 (案例 打印 7的倍数,能被7整除,包含7的数)

7的倍数 如 49

包含7 如 47/57 70、71、72…

for (int i = 0; i < 100; i++) {
  if (i % 7 == 0) {  // 被7整除
    // continue;
    cout << i << endl;
  }
  else if (i / 10 == 7) {  // 70-79
    // continue;
    cout << i << endl;
  }
  else if (i % 10 == 7) {  // 个位是7 47/57
    // continue;
    cout << i << endl;
  }
}

输出

0
7
14
17
21
27
28
35
37
42
47
49
56
57
63
67
70
71
72
73
74
75
76
77
78
79
84
87
91
97
98

goto 语句

一般不建议使用 gotogoto 会直接跳转到 指定的语句

for (int i = 0; i < 10; i++) {
  if (i == 5) goto FLAG;
}

FLAG:
  cout << "goto falg" << endl;

输出

goto falg

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议,转载请注明出处。