我想使用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();
}发布于 2016-08-08 21:50:09
可以将std::ostream方法与像mpfr_as_printf或mpfr_get_str这样的mpfr函数一起使用。但是,它需要额外的字符串分配。
#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);
}发布于 2016-08-08 21:39:15
经过不多的工作后,我发现下面的代码替换了下面的4行代码:
FILE* my_file;
my_file = fopen("output.txt", "w");
mpfr_out_str(my_file, 2, 0, x, MPFR_RNDN);
fclose(my_file);https://stackoverflow.com/questions/38830249
复制相似问题