定义 PI 值
我正在开发一个新项目,我正在尝试编写最干净、最容易阅读并且希望最高效的代码。
我需要使用 PI 但显然它没有在 math.h 中定义。所以我读到了这样做:
const double PI = atan(1.0)*4
但我收到此错误:
函数调用不能出现在常量表达式中
有什么想法吗?如何获得 PI 作为常数?
另外,我正在尝试通过这个项目尽可能多地学习,所以如果您也能解释为什么您的答案有效,那就太好了。谢谢!
I am working on a new project and I am trying to write the cleanest, easiest to read and hopefully, most efficient, code I can.
I need to use PI but apparently it isn't defined in math.h. So I read about doing this:
const double PI = atan(1.0)*4
But I get this error:
A function call cannot appear in a constant-expression
Any ideas on why? How can I get PI as a constant?
Also, please, I am trying to learn as much as I can with this project, so it would be great if you could also explain why your answer would work. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
汇编语言怎么样?
它只是使用浮点指令的替代方案
How about assembly language ?
It is just alternative using Floating-Point Instruction
怎么样:
在我看来,这比
atan(1.0)*4
更干净、更容易阅读、更高效。How about:
This seems to me to be cleaner, easier to read, and more efficient than
atan(1.0)*4
.您错误地标记了问题。在 C++ 中,以下内容是明确定义的并且可以编译:
但在 C 中,不允许在文件范围内进行初始化。
在 C 中,您需要使用非标准宏(例如 GCC 中的
M_PI
),创建您自己的适当宏或文字(Ned Batchelder 已经为您完成了困难的部分),或者在您自己的函数中尽早初始化它。You have mis-tagged the question. In C++ the following is well-defined and will compile:
But in C, initializers at file scope are not allowed to.
In C you'll either need to use a non-standard macro (such as
M_PI
in GCC), create your own appropriate macro or literal (Ned Batchelder has done the hard part for you), or initialize it in your own function at an appropriately early enough time.您无法为全局 const double 调用函数,因为该常量需要在编译时求值。在运行时
atan()
可以是任何东西。您可以安排在启动时调用一次,但使用已经可用的实际 PI 常数会更好。(实际上直接使用
M_PI
也很好)编辑:一年多后,我花了很多评论点赞并重新阅读了我自己的答案,才明白为什么人们对我关于常量的陈述感到愤怒。我跳过了一个步骤:正如每个人都说的那样,您可以在运行时初始化 const double 就像 double 一样容易。 但是,如果您使用全局变量(而不是常量表达式)来存储 pi,您将失去一些优化机会。使用
gcc
进行的一些实验表明,这甚至没有我想象的那么糟糕,这提出了一个全新的问题......You can't call a function for a global
const double
because the constant needs to be evaluated at compile time. At runtimeatan()
could be anything. You could arrange for it to be called once at startup, but using an actual PI constant that's already available is better.(actually using
M_PI
directly would also be good)EDIT: It took many comment upvotes and re-reading my own answer over a year later to see why people were up in arms about my statement about constants. I was jumping over a step: As everyone is saying you can initialize
const double
at runtime just as easily asdouble
. However, if you are using a global variable (instead of a constant expression) to store pi you will defeat some optimization opportunities. Some experiments withgcc
suggest this isn't even as bad as I thought, which suggests a whole new question...