简体   繁体   中英

How do I set precision to 100 digits in c++?

I am sorry, I have a very basic question.

Here is a very simple calculation, an integer (22) divided by another integer (7). I would like the c++ code use exactly 100 digits of precision both in the actual calculation inside the code and in the output value. Using the Maple program, I get

restart;
Digits:=100;
evalf(22/7);

And the answer I get is,

3.142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857142857143

But I use the following c++ code and get something different answer. This simply adds zeros after few actual digits, which is completely wrong. Below is my c++ code.

#include <iostream>
 using namespace std;
 int main()
 {
     cout << fixed;
     cout.precision(100);
     cout << "22/7 = " << 22/(double)(7) << endl;
     return 0;
}

Using the Maple program, I get

Maple is a special tool that beside others:

Support for symbolic and numeric computation with arbitrary precision

On another side C++ is a general purpose programming language. As a language it supports floating point arithmetic which has limited precision. You cannot expect to throw arbitrary precision there and expect the same result as you get in Maple. So you need to use an arbitrary precision library (which is not part of standard C++) or switch to a different language that supports it by design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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