C++ 令#define和关键字const定义符号变量的不同

#include <iostream>
using namespace std;
#define PI 3.14159;
void main()
{
const int R =10;
double p,s;
p = 2*R*PI;
s = R*R*PI;
cout<<"半径:"<<R<<endl;
cout<<"周长:"<<p<<endl;
cout<<"面积:"<<s<<endl;
}

用编译预处理命令#define和关键字const定义符号变量为什么会有不同的结果
#include <iostream>
using namespace std;
const PI=3.14159;
void main()
{
const int R =10;
double p,s;
p = 2*R*PI;
s = R*R*PI;
cout<<"半径:"<<R<<endl;
cout<<"周长:"<<p<<endl;
cout<<"面积:"<<s<<endl;
}

用 #define PI 3.14159; 输出的R=10,P=62.8318,S =341.159
用 const PI=3.14159; 输出的R=10,P=2.00858e+009,S=1.45298e+009
为什么会这样呢

输出结果上没有区别。但是在实际编译和运行时是不同的:预处理命令#define是在编译前便已经将宏调用替换为宏体了,所以是变量。但是const定义的量只有在程序加载到内存中后才确定它的值,也就是具有变量的性质,只不过它的值不允许更改而已。追问

#include
using namespace std;
const PI=3.14159;
void main()
{
const int R =10;
double p,s;
p = 2*R*PI;
s = R*R*PI;
cout<<"半径:"<<R<<endl;
cout<<"周长:"<<p<<endl;
cout<<"面积:"<<s<<endl;
}

用 #define PI 3.14159; 输出的R=10,P=62.8318,S =341.159
用 const PI=3.14159; 输出的R=10,P=2.00858e+009,S=1.45298e+009
为什么会这样呢

追答

楼上,const与#define不同,#define定义量不需要指定数据类型,但是const定义常量需要指定数据类型。因此你的程序中:const PI=3.14159应该是const double PI=3.14159

温馨提示:内容为网友见解,仅供参考
第1个回答  2011-03-17
1.#define定义的是符号常量,在编译时替换。const定义的是变量,在程序执行时分配存储空间。
2.
#define n 10
int a[n];//语法正确;

const int n=10;
int a[n];//语法错误;
第2个回答  2011-03-17
用编译预处理命令#define 默认代替的是字符型
const定义符号变量 就取决你定义的类型
相似回答