🧑🏻‍💻 博世

C++变量

🇨🇳每日一言:

## Stay hungry, Stay foolish

变量的意义

  • 方便我们管理内存空间 ## 变量创建的语法
  • 数据类型 变量名 = 变量的初始值;
  • 例如:int a = 10 ;
int a = 10;

变量的使用

# include<iostream>
        using namespace std;
        int main(){
            int a = 10 ;
            cout << "a=" << a << endl;  
            cin.get();

        }

运行结果

image.png

常量

  • 用于记录程序中不可变更的数据
  • C++中定义常量常用两种方式
    1. #define 宏常量 :#define 常量名 常量值 > 通常在文件上方定义,表示一个常量

    2. const 修饰的变量: const 数据类型 常量名 = 常量值 > 通常在变量定以前加const,修饰变量为常量,不可更改。

  • 示例1:
# include<iostream>
        using namespace std;
        //常量的定义方式:1.define 2.const 变量
        #define day 7
        
        int main(){
           
            cout << "一周有" << day << "天" << endl;
            
        
        }
  • 更改常量值会报错:表达式必须是可修改的左值
    > 常量不可修改值
image.png
  • 示例2
# include<iostream>
        using namespace std;
        //常量的定义方式:1.define 2.const 变量

        #define day 7

        int main(){
            const int month = 12 ;    
            cout << "一周有" << day << "天" << endl;   
            cout << "一年有" << month << "个月" << endl;   

        }
  • 运行结果:
一周有7天
        一年有12个月
  • 修改常量会报错:表达式必须是可修改的左值
image.png