Converting a precision double to a string

2019-05-14 19:03发布

问题:

I have a large number in c++ stored as a precise double value (assuming the input 'n' is 75): 2.4891e+109

Is there any way to convert this to a string or an array of each individual digit?

Here's my code so far, although it's not entirely relevant to the question:

int main(){

    double n = 0; 
    cout << "Giz a number: ";
    cin >> n;
    double val = 1;
    for(double i = 1; i <= n; i++){
        val = val * i;
    }
    //Convert val to string/array here?
}

回答1:

std::stringstream str;
str << fixed << setprecision( 15 ) << yournumber;

You may also be interested in the scientific format flag.

C++11 also has a few interesting functions std::to_string which you may want to check out!



回答2:

What's wrong with the standard way?

std::stringstream ss;
ss << val;
std::string s = ss.str();

Additionally, C++11 allows:

std::string s = std::to_string(val);

If you need performance you might find that the memory allocations involved above are too expensive, in which case you could resort to snprintf, the deprecated strstream, or perhaps direct use of the num_put facet. For example:

char c[30];
std::snprintf(c,sizeof c,"%e",val);


回答3:

You will find that the double value is not as precise as you think. It only contains 53 bits of precision, or about 15-17 digits; after that it starts rounding each result. Your number requires much more precision than that if you want an exact answer, 92 digits actually or 364 bits.



回答4:

std::cout << setprecision(5) << val;

as in http://www.cprogramming.com/tutorial/iomanip.html