首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使我的pi生成代码在300时被切断?

如何使我的pi生成代码在300时被切断?
EN

Stack Overflow用户
提问于 2022-11-25 17:17:51
回答 1查看 35关注 0票数 0

我正在尝试写一个程序,允许pi被萌发到300位数,但我似乎不知道如何在300位数的时候切断它。

到目前为止,代码已经永远运行了,而且我尝试过的任何其他方法都没有像在specfiec时中断一样工作,但是这并不是我所需要的。

代码语言:javascript
复制
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>

using namespace boost::multiprecision;

class Gospers
{
    cpp_int q, r, t, i, n;

public:    

    // use Gibbons spigot algorith based on the Gospers series
    Gospers() : q{1}, r{0}, t{1}, i{1}
    {
        ++*this; // move to the first digit
    }

    // the ++ prefix operator will move to the next digit
    Gospers& operator++()
    {
        n = (q*(27*i-12)+5*r) / (5*t);

        while(n != (q*(675*i-216)+125*r)/(125*t))
        {
            r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);
            q = i*(2*i-1)*q;
            t = 3*(3*i+1)*(3*i+2)*t;
            i++;

            n = (q*(27*i-12)+5*r) / (5*t);
        }

        q = 10*q;
        r = 10*r-10*n*t;

        return *this;
    }

    // the dereference operator will give the current digit
    int operator*()
    {
        return (int)n;
    }
};

int main()
{
    Gospers g;

    std::cout << *g << ".";  // print the first digit and the decimal point

    for(300;) // run forever
    {
        std::cout << *++g;  // increment to the next digit and print
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-25 17:40:25

您正在声明您生成了300位数字,但是这个for-循环中断了:

代码语言:javascript
复制
for(300;)

它不是有效的C++代码,因为换环的结构如下:

代码语言:javascript
复制
for ( declaration ; expression ; increment)

虽然所有三个段都是可选的,但是有效的语法至少需要两个分号(;)。

要实现重复序列300次的for循环,您需要一个for循环,如下所示:

代码语言:javascript
复制
for (int i = 0; i < 300; ++i)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74576092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档