为了确定从3.14159开始第一次获取pi需要多少个术语,我编写了以下程序,将术语计算为(pi = 4 - 4/3 + 4/5 - 4/7 + ...)

我的问题是结果达到了146063个术语,但是当我检查时,在此之前有很多类似的pis开始。

//piEstimation.cpp
//estima mathematical pi and detrmin when
//to get a value beganing with 3.14159

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main(){
    //initialize vars
    double denominator{1.0};
    double pi{0};
    string piString;
    double desiredPi;
    int terms;
    int firstDesiredTerm;

    //format output floating point numbers to show 10 digits after
    // decimal poin
    cout << setprecision (10) <<fixed;

    for (terms = 1;  ; terms++){
        if(0 == terms % 2){ //if term is even
            pi -= 4/denominator;
        }
        else{ //if term is odd
            pi += 4/denominator;
        }

        // draw table
        cout << terms << "\t" << pi << endl;

        //determin first time the pi begains with 3.14159
        piString = to_string(pi).substr(0,7);
        if(piString == "3.14159"){
             firstDesiredTerm = terms;
             desiredPi = pi;
             break;
        }
        denominator += 2;
    }//end for

    cout << "The first time that pi value begans with 3.14159 "
        << "the number of terms are " << firstDesiredTerm << " and pi value is  "<< desiredPi <<endl;
}//end main

最佳答案

如果x,则数字x >= 3.14159 && x < 3.1416以3.14159开头。无需使用字符串和比较字符。 to_string必须使用某种舍入运算。如果没有字符串,算法将在136121个步骤后找到结果

#include <iostream>
#include <iomanip>

int main(){
    //initialize vars
    double denominator{1.0};
    double pi{0};
    double desiredPi;
    int terms;
    int firstDesiredTerm;

    //format output floating point numbers to show 10 digits after
    // decimal poin
    std::cout << std::setprecision (20) << std::fixed;

    for (terms = 1;  ; terms++){
        if(0 == terms % 2){ //if term is even
            pi -= 4/denominator;
        }
        else{ //if term is odd
            pi += 4/denominator;
        }

        // draw table
        std::cout << terms << "\t" << pi << std::endl;

        if(pi >= 3.14159 && pi < 3.1416){
             firstDesiredTerm = terms;
             desiredPi = pi;
             break;
        }
        denominator += 2;
    }//end for

    std::cout << "The first time that pi value begans with 3.14159 "
        << "the number of terms are " << firstDesiredTerm
        << " and pi value is  "<< desiredPi << std::endl;
}

输出:
The first time that pi value begans with 3.14159 the number of terms are 136121 and pi value is  3.14159999999478589672

在这里,您可以看到to_string如何舍入结果:
#include <iostream>
#include <iomanip>
#include <string>

int main(){
    std::cout << std::setprecision (20) << std::fixed;
    std::cout << std::to_string(3.14159999999478589672) << '\n';
}

输出:
3.141600

您可以在cppreference上阅读



您可以在cppreference上阅读



这意味着std::to_string在6位数字后四舍五入。

关于c++ - 如何以3.14159开始查找第一个pi,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62466381/

10-11 04:25