在 C/C++ 中以指数形式将浮点数声明为宏的正确方法是什么?
What is the proper way of declaring a floating point number in exponential form as a macro in C/C++?
我试图创建一个非常简单的程序来计算C++中两个物体之间的引力。所以我想为 G 声明一个值等于 6.754*10^-11 的宏,我使用了这个:
#define G 6.754e-11.0;
但它产生了许多杂散错误,如下所示:
cd '~/Desktop/CS/C++/Other PSETS'
g++ gravity.cpp -o gravity
输出:
gravity.cpp:5:28: error: stray ‘342’ in program
#define G (6.754)*pow(10.0,��11.0);
^
gravity.cpp:10:52: note: in expansion of macro ‘G’
float gforce(float m1,float m2,float r){return G*m1*m2/(r*r);}
^
gravity.cpp:5:29: error: stray ‘210’ in program
#define G (6.754)*pow(10.0,��11.0);
^
gravity.cpp:10:52: note: in expansion of macro ‘G’
float gforce(float m1,float m2,float r){return G*m1*m2/(r*r);}
^
gravity.cpp:5:30: error: stray ‘222’ in program
#define G (6.754)*pow(10.0,�11.0);
^
gravity.cpp:10:52: note: in expansion of macro ‘G’
float gforce(float m1,float m2,float r){return G*m1*m2/(r*r);}
因此,我决定使用数学库函数cmath
来使用pow()
,但它仍然没有任何用处。我该怎么做才能创建这样的宏?
注意:我在 Ubuntu 上使用 G++,如下所示:
g++ --version
输出:
g++ (Ubuntu 7.2.0-8ubuntu3) 7.2.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
错误消息
stray ‘342’ in program
表示您的程序包含C++语法不允许的字符(从技术上讲,它不在"基本源字符集"之外)。 三位数字是问题字节数值的八进制编码。 你连续得到了其中的三个,所以有问题的字节序列是0342 0210 0222
,这是Unicode字符U+2212减号的UTF-8编码。
没错。您不得在C++中使用减号。 必须改用 U+002D 连字符-MINUSes。
要解决这部分问题,请在编辑器中转到该行
#define G 6.754e-11.0;
减号上的退格键并重新键入。 这可能是因为您从使用花哨(我的意思是"不仅仅是普通 ASCII")排版的网页或 PDF 中复制并粘贴了数字。
您仍然需要解决其他几个问题。 那个分号根本不应该存在,因为#define
在行尾结束。 C++ 中浮点文字的指数必须是整数。 所以你真正应该拥有的是
#define G 6.754e-11
可以说,为此使用const
变量也更好,因为您不需要宏:
const double G = 6.754e-11;
(请注意,分号现已返回)...但我足够老派,不反对对数字常量使用宏。
这里绝对没有理由使用pow
。
相关文章:
- C++避免重复声明的语法是什么
- 是什么原因导致它无法编译?它是声明签名还是在函数本身的实现中
- 这个额外的关键字在这个 c++ 类声明中是什么意思?
- * 和 ** 在 C++ 函数声明中是什么意思?
- 在将函数声明为友元时,尖括号的含义是什么?
- 如何声明一个标准::提升直方图的向量?提升直方图的类型是什么?
- 假设声明中某些上下文中需要的名称查找规则是什么
- 用相同的参数声明两个构造函数的最偶像化的方法是什么?
- C++中这个声明的向量是什么意思
- boost::hana 转发声明标头的用例是什么?
- 这个嵌套结构声明是什么意思?
- 以下的 c# dll 导入声明是什么?
- 这个 c++ 类声明是什么意思
- 这个C++函数声明是什么
- 请解释一下这个朋友声明是什么意思
- 函数调用前的类型声明是什么意思?
- 这个论点的声明是什么意思:"type (*name1) (const type& name2)"?
- c++中的这种声明是什么意思
- c++中的这种声明是什么意思?
- 以下声明是什么意思