跳到主要内容

常量

常量分两种,一种直接写出来的,如123,3.14,"abc",'a'这种一般常量。一种是有名字的,定义出来的常量

一般常量

在写程序时,直接写在代码里的数字,字符,字符串都是常量

整数常量

int a=123;//123 默认是int类型常量
int b=011;//八进制 代表9
int c=0x11;//十六进制 代码17
long long d=123ll;//long long 常量123
long long d=2147483647123;//2147483647123超过int,自动升级为long long
unsigned int e=-1u;//无符号常量 -1u代表4294967295
long long常量的作用1
long long a=2147483647+1; //-2147483648 越界
long long b=2147483647ll+1;//2147483648 没越界

int+int 得到的结果是int类型,所以是先越界,再赋值给a
long long +int 得到的是long long

long long常量的作用2
long long a=2;
cout<<max(a,3); //编译错误

a是long long的,无法和int比较

long long a=2;
cout<<max(a,3ll);//成功输出3

类型相同,才能用max比较

小数常量

cout<<3.14<<endl;//3.14
cout<<3.1234e2<<endl;//312.34 科学记数法 e2代表10的2次方
cout<<3.1234E2<<endl;//312.34 大小写E都可以
cout<<3.123f<<endl;//float类型小数常量

字符常量

cout<<'0'<<'A'<<'B'<<endl;//普通字符
cout<<'\n'<<'\''<<'\\';//转义字符

字符串常量

cout<<"hello world\n";//
cout<<"hello\
world";//行末用\ 连接下一行

布尔常量

if(true){
cout<<111;
}
cout<<false;

定义常量

const int N = 100;
const double PI=3.14159;

const 声明的常量只能使用,无法改变,一般都是大写字母,放在程序的任意位置都可以

#include <iostream>
#define PI 3.14159 //常量PI
using namespace std;
int main(){
double r=3;
cout<<2*PI*r;
return 0;
}

一般放在主函数外,原理是替换,将PI替换成3.14159后运行

define的功能异常强大

不要只以为他是用来定义常量的,它还能定义数据类型,比如long long很长,写起来很麻烦,你就可以定义ll来代表long long。甚至它还可以用来定义for循环,自定义语法

C++已经为我们提供的常量

  • INT_MAX int的最大值
  • INT_MIN int的最小值
  • LLONG_MAX long long的最大值
  • LLONG_MIN long long的最小值