在 C/C++ 中以指数形式将浮点数声明为宏的正确方法是什么?

What is the proper way of declaring a floating point number in exponential form as a macro in C/C++?

本文关键字:声明 是什么 方法 浮点数 C++ 指数      更新时间:2023-10-16

我试图创建一个非常简单的程序来计算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