常量定义后不能改变
用define来定义
eg:1
#include <iostream>
using namespace std;
#define PAI 3.1415 //不需要写等号
int main()
{
double r = 2;
cout << "S=" << PAI*r*r <<endl;
return 0;
}
代码中PAI为常量后面数值不会改变,不管何时计算都是3.1415
也可以将变量定义为常量
需要用const来定义
#include <iostream>
using namespace std;
#define day 7
int main(){
const int month = 7;
cout <<"month" << endl;
}
此时month的数值不会改变一直等于7
eg:2
#include <iostream>
#include <cmath> //函数计算需要用到
using namespace std;
double root(const double x, const double y)
{
if(x>=y) return sqrt(x-y); //X大于等于Y时,计算x-Y的平方根
else return 0;
}
int main()
{
double a, b;
cin >> a >> b; //输入两个数
cout << root (a,b) <<endl;
return 0;
}
主函数a,b传给x,y后,因为x,y加了const所以x,y数值不再改变由变量变为常量