C++中的long double类型

虽然long double提供了更高的精度和更大的范围,但它的兼容性和移植性不好。不同的编译器和平台对long double的实现有所不同。因此,在跨平台开发时,使用long double需要特别小心,确保在所有目标平台上都能正确运行。

long double类型sizeof()实测:存储空间

测试代码:

#include <iostream>

int main()
{
    std::cout << sizeof(long double) << std::endl;
    return 0;
}

用圆周率测试long double

测试代码:

#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>

int main()
{
    std::cout << "sizeof(long double):"<<sizeof(long double) << std::endl;
    // PI,有效十进制位数40,对应的字符串
    std::string str_pi = "3.141592653589793238462643383279502884197";

    //测试long double 的变量,需要转为对应的字符串
    long double pi=3.141592653589793238462643383279502884197L;
    std::ostringstream out;
    out.precision(39);
    out << std::fixed << pi;
    //long double类型 pi 对应的字符串
    std::string str_pi_from_long_double = out.str();
    std::cout <<"pi:                 "<< str_pi << std::endl;
    std::cout <<"pi_from_long_double:"<< str_pi_from_long_double << std::endl;

    //计算long double 精度
    int n=2;//精度
    while(n<40) {
        if (str_pi[n]!=str_pi_from_long_double[n]) {
            std::cout << "The number of significant digits in long double is:" <<n-1<< std::endl;
            break;
        }else {
            n++;
        }
    }
}

g++:

sizeof(long double):16
pi:                 3.141592653589793238462643383279502884197
pi_from_long_double:3.141592653589793238512808959406186204433
The number of significant digits in long double is:19	`

bcc32c:

sizeof(long double):10
pi:                 3.141592653589793238462643383279502884197
pi_from_long_double:3.141592653589793238000000000000000000000
The number of significant digits in long double is:19

bcc64x:

sizeof(long double):8
pi:                 3.141592653589793238462643383279502884197
pi_from_long_double:3.141592653589793115997963468544185161591
The number of significant digits in long double is:16

结果:

  • bcc32c:用80位存储19位有效数字的pi
  • g++ :用 128位存储pi,但只有19位有效
  • bcc64x:用64位存储pi

如果传一个double(字面量末尾没有加L):

long double pi=3.141592653589793238462643383279502884197;

g++:

pi:                 3.141592653589793238462643383279502884197
pi_from_long_double:3.141592653589793115997963468544185161591
The number of significant digits in long double is:16

bcc32c:

sizeof(long double):10
pi:                 3.141592653589793238462643383279502884197
pi_from_long_double:3.141592653589793116000000000000000000000
The number of significant digits in long double is:16

bcc64x:

sizeof(long double):8
pi:                 3.141592653589793238462643383279502884197
pi_from_long_double:3.141592653589793115997963468544185161591
The number of significant digits in long double is:16

long double相关参考资料

正文完
 0
评论(没有评论)