定义PI的值 [英] Defining value of PI

查看:418
本文介绍了定义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.

我需要使用PI,但显然没有在math.h中定义。所以我阅读了这样做:

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

但我收到此错误:


调用不能出现在常量表达式

A function call cannot appear in a constant-expression

任何想法为什么?我如何获得PI作为一个常数?

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!

推荐答案

#include <math.h>

const double PI = M_PI;

您不能为全局 const double ,因为常量需要在编译时进行求值。在运行时 atan()可以是任何东西。

You can't call a function for a global const double because the constant needs to be evaluated at compile time. At runtime atan() 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.

(实际上使用 M_PI 直接也会是好的)

(actually using M_PI directly would also be good)

编辑:一个多年后,我花了很多评论upvotes和重新阅读我自己的答案,关于我关于常量的声明。我跳过一步:因为每个人都说你可以在运行时初始化 const double ,就像 double 一样容易。 但是,如果您使用全局变量(而不是常量表达式)存储pi,则会失败一些优化机会。使用 gcc 的一些实验表明,这甚至不如我想象的那样糟糕,这暗示了一个全新的问题...

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 as double. However, if you are using a global variable (instead of a constant expression) to store pi you will defeat some optimization opportunities. Some experiments with gcc suggest this isn't even as bad as I thought, which suggests a whole new question...

这篇关于定义PI的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆