我有以下代码,根据您选择的项数,计算出6 * [1 + 1 /(2 ^ 2)+ 1 /(3 ^ 2).... 1 /(n ^ 2)]。在这种情况下,我将使用100个术语。如果得到输出应该是什么,是否有办法使用现有代码确定使用了多少个术语来获得该输出?

#include <stdio.h>
#include <math.h>

int main(int argc, const char * argv[]) {

    long double square = 0;
    for (int i = 1; i <= 100; i++) {
        long double squareExp = i*i;
        square += 1/(squareExp);
    }

    long double sixTimes = 6 * square;
    long double squareRoot = sqrt(sixTimes);

    printf("%.8Lf", squareRoot);

    return 0;
}


我试着制作它,以便获得所需的输出(3.141592),对其进行平方并除以6以得到负平方根和(* 6),然后尝试运行以下代码:

double temp = 3.141592 * 3.141592;
double tempB = temp / 6;
printf("%f\n", tempB);
int reachedZero = 0;
int valueOfN = 0;

long double square = 0;
while (square > 0) {
    int i = 1;
    square -= 1/i;
    i++;
    if (square <= 1) {
        reachedZero = 1;
        valueOfN = i;
        break;
    }
}

printf("%i", valueOfN);



return 0;


}

我不知道该怎么办。我要取数字(除去平方根并乘以6后),然后减去从1开始的数字,然后是1/4,然后是1/9,然后是1/16 ... 1 /(n ^ 2 ),直到数字变为负数为止。一旦发生这种情况,我就设置一个标志,并且知道要达到该#号需要多少个术语。然后,将特定计数器设置为变量,然后将其打印出来。

最佳答案

@EugeneSh。这对我来说是一个可行的解决方案。基本上将我正在寻找的pi输出与我的循环匹配,每次都检查一次。可以将for循环更改为while循环,但是这种方式可以正常工作。

int main(int argc, const char * argv[]) {

    long double square;
    for (long i = 1; i>=1; i++) {
        square += 1.0/(i*i);
        long double sixTimes = sqrt(6 * square);
        if (sixTimes >= 3.141592) {
            printf("%li", i);
            break;
        }
    }
    return 0;
}

关于c++ - 对于给定的输出,程序计算中使用了多少项?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30334345/

10-14 15:20
查看更多