简体   繁体   English

C ++的大价值

[英]Big values in C++

I'm doing a fibonacci and I want to save all the numbers in a .txt, i have done the code but when the cicles gets big values the program express it as an exponential, and then gets bigger as .INF. 我正在做一个斐波那契,我想将所有数字保存在.txt中,我已经完成了代码,但是当cicles获得较大的值时,程序会将其表示为指数,然后变为.INF。 How I can save the entry number? 如何保存条目号?

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()  {

    ofstream File;
    File.open("fibo.txt");

    double val0 = 0, val1 = 1, i = 0, n, out;
    cout << "Enter n of Fibonacci(n): ";
    cin >> n;

    while (i < n)   {
        if (n == 0) {
            File << i << "- " << 0 << endl;
            i++;
        }
        else    {
            out = val0 + val1;
            val0 = val1;
            val1 = out;
            i++;
            File << i << "- " << val0 << endl;
            }
        }
        File.close();
        return 0;
    }

You can use boost::multiprecision , it's very intuitive and easy to use. 您可以使用boost :: multiprecision ,它非常直观且易于使用。 Your code can be modified by changing (only) a couple of lines: 您可以更改(仅)几行代码来修改您的代码:

#include <boost/multiprecision/cpp_int.hpp> // need this

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
using namespace boost::multiprecision;

int main()
{

    ofstream File;
    File.open("fibo.txt");

    cpp_int val0 = 0, val1 = 1, out; // arbitrary precision integers
    int i = 0, n;
    cout << "Enter n of Fibonacci(n): ";
    cin >> n;

    while (i < n)   {
        if (n == 0) {
            File << i << "- " << 0 << endl;
            i++;
        }
        else    {
            out = val0 + val1;
            val0 = val1;
            val1 = out;
            i++;
            File << i << "- " << val0 << endl;
        }
    }
    File.close();
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM