簡體   English   中英

從MPFR打印到文件

[英]Print to file from MPFR

我想使用MPFR將計算結果打印到文件中,但我不知道如何。 MPFR用於高精度地執行浮點運算。 要打印mpfr_t號,請使用以下功能:

size_t mpfr_out_str (FILE *stream, int base, size tn, 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);
  }

經過不多的工作之后,我發現它可以代替下面的4行代碼:

FILE* my_file;
my_file = fopen("output.txt", "w");
mpfr_out_str(my_file, 2, 0, x, MPFR_RNDN);
fclose(my_file);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM