首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从MPFR打印到文件

从MPFR打印到文件
EN

Stack Overflow用户
提问于 2016-08-08 21:16:53
回答 2查看 185关注 0票数 0

我想使用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,那么数字将如我所希望的那样打印到屏幕上,但我不知道如何将其写入文件中。

代码语言:javascript
复制
#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();
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-08 21:50:09

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

代码语言:javascript
复制
  #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);
  }
票数 1
EN

Stack Overflow用户

发布于 2016-08-08 21:39:15

经过不多的工作后,我发现下面的代码替换了下面的4行代码:

代码语言:javascript
复制
FILE* my_file;
my_file = fopen("output.txt", "w");
mpfr_out_str(my_file, 2, 0, x, MPFR_RNDN);
fclose(my_file);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38830249

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档