用GCC和C++实现类型"long double"11

use*_*501 6 c++ double

我已经尝试搜索long double的信息,到目前为止,我知道它由编译器以不同的方式实现.

在Ubuntu(XUbuntu)Linux 12.10上使用GCC时,我得到了这个:

double PId = acos(-1);
long double PIl = acos(-1);
std::cout.precision(100);

std::cout << "PId " << sizeof(double) << " : " << PId << std::endl;
std::cout << "PIl " << sizeof(long double)  << " : " << PIl << std::endl;
Run Code Online (Sandbox Code Playgroud)

输出:

PId 8  : 3.141592653589793115997963468544185161590576171875
PIl 16 : 3.141592653589793115997963468544185161590576171875
Run Code Online (Sandbox Code Playgroud)

任何人都明白为什么他们输出(几乎)相同的东西?

sch*_*der 8

根据acos引用,long double只有当你传递long double给它时它才会返回.你也必须std::acos像狒狒一样使用.这对我有用:

#include <cmath>
#include <iostream>

int main() {

  double PId = acos((double)-1);
  long double PIl = std::acos(-1.0l);
  std::cout.precision(100);

  std::cout << "PId " << sizeof(double) << " :  " << PId << std::endl;
  std::cout << "PIl " << sizeof(long double)  << " : " << PIl << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

PId 8  : 3.141592653589793115997963468544185161590576171875
PIl 12 : 3.14159265358979323851280895940618620443274267017841339111328125

         3.14159265358979323846264338327950288419716939937510582097494459
Run Code Online (Sandbox Code Playgroud)

最后一行不是输出的一部分,并包含pi到此精度的正确数字.


ems*_*msr 5

要获得正确的有效位数std::numeric_limits.在C++ 11中,我们有digits10十进制有效数字(相反,digits它给出了有效).

#include <cmath>
#include <iostream>
#include <limits>

int
main()
{
  std::cout.precision(std::numeric_limits<float>::digits10);
  double PIf = acos(-1.0F);
  std::cout << "PIf " << sizeof(float) << " :  " << PIf << std::endl;

  std::cout.precision(std::numeric_limits<double>::digits10);
  double PId = acos(-1.0);
  std::cout << "PId " << sizeof(double) << " :  " << PId << std::endl;

  std::cout.precision(std::numeric_limits<long double>::digits10);
  long double PIl = std::acos(-1.0L);
  std::cout << "PIl " << sizeof(long double)  << " : " << PIl << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

在x86_64 linux上,我得到:

PIf 4 :  3.14159
PId 8 :  3.14159265358979
PIl 16 : 3.14159265358979324
Run Code Online (Sandbox Code Playgroud)