gpt4 book ai didi

c++ - 从 MPFR 打印到文件

转载 作者:行者123 更新时间:2023-11-28 05:33:43 24 4
gpt4 key购买 nike

我想打印使用 MPFR 的计算结果到文件,但我不知道如何。 MPFR 用于进行高精度的浮点运算。要打印 mpfr_t 数字,您可以使用以下函数:

size_t mpfr_out_str (FILE *stream, int base, size t n, mpfr t op, mp rnd t rnd)

我想我的问题是我不理解 FILE* 对象以及它们与 fstream 对象的关系。

如果我将 mpfr_out_str 行中的 my_file 更改为 stdout 那么该数字将如我所希望的那样打印到屏幕上,但我没有不知道如何将其写入文件。

#include <mpfr.h>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
mpfr_t x;
mpfr_init(x);
mpfr_set_d(x, 1, MPFR_RNDN);

ofstream my_file;
my_file.open("output.txt");
mpfr_out_str(my_file, 2, 0, x, MPFR_RNDN);
my_file.close();
}

最佳答案

可以将 std::ostream 方法与 mpfr 函数(如 mpfr_as_printf 或 mpfr_get_str)一起使用。但是,它需要额外的字符串分配。

  #include <mpfr.h>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
mpfr_t x;
mpfr_init(x);
mpfr_set_d(x, 1, MPFR_RNDN);

ofstream my_file;
my_file.open("output.txt");

char* outString = NULL;
mpfr_asprintf(&outString, "%RNb", x);
my_file << outString;
mpfr_free_str(outString);
my_file.close();

mpfr_clear(x);
}

关于c++ - 从 MPFR 打印到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38830249/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com