Jef*_*eff 6 c++ floating-point precision
我正在尝试在GCC中使用quadmath库.我有一个复杂的双值我想要转换成相应的四精度复数,__complex128.以下是最小(非)工作示例:
#include <quadmath.h>
#include <complex>
#include <stdio.h>
using namespace std::complex_literals;
int main(){
std::complex<double> x = 1 + 2i;
std::printf("x = %5.5g + %5.5g\n", x.real(), x.imag());
__complex128 y = 2+2i;
y = x;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译此代码时
g++ test.cpp -lquadmath -o test
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
test.cpp:10:6: error: cannot convert 'std::complex<double>' to '__complex128 {aka __complex__ __float128}' in assignment
y = x;
Run Code Online (Sandbox Code Playgroud)
如果我尝试用显式类型转换替换赋值行,
y = (__complex128) x;
Run Code Online (Sandbox Code Playgroud)
我得到了类似的错误
test.cpp:10:21: error: invalid cast from type 'std::complex<double>' to type '__complex128 {aka __complex__ __float128}'
y = (__complex128) x;
Run Code Online (Sandbox Code Playgroud)
如何在这两种类型之间进行转换?
我猜您正在使用 GCC,在这种情况下您可以使用__real__和__imag__扩展来设置您的各个组件__complex128:
__complex128 y;
__real__ y = x.real();
__imag__ y = x.imag();
Run Code Online (Sandbox Code Playgroud)
这在 Clang 中也适用于 __complex64(Clang 尚不支持 __complex128)。