Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用c+计算PI数+;程序 //PI=4-(4/3)+(4/5)-(4/7)。。。第一次陈述100条 #包括 #包括 使用名称空间std; int main(){ 双PI=0.0; INTA=1; 因为(int i=1;i_C++ - Fatal编程技术网

C++ 用c+计算PI数+;程序 //PI=4-(4/3)+(4/5)-(4/7)。。。第一次陈述100条 #包括 #包括 使用名称空间std; int main(){ 双PI=0.0; INTA=1; 因为(int i=1;i

C++ 用c+计算PI数+;程序 //PI=4-(4/3)+(4/5)-(4/7)。。。第一次陈述100条 #包括 #包括 使用名称空间std; int main(){ 双PI=0.0; INTA=1; 因为(int i=1;i,c++,C++,4/a是一个整数除法,您的转换double(…)发生在该除法之后,因此结果永远不会在小数点之后。例如,4/5导致0 您需要将4从整数更改为双精度4。在double(4/a)中,4/a部分计算为一个整数,当您将其转换为double时,它已经被截断。您要做的是4.0/a,而不需要显式转换。代码中的问题是在计算值时: // PI = 4 - (4/3) + (4/5) - (4/7) ... for 100 first statements #include <iostream> #inc

4/a
是一个整数除法,您的转换
double(…)
发生在该除法之后,因此结果永远不会在小数点之后。例如,
4/5
导致
0


您需要将
4
从整数更改为双精度
4。

double(4/a)中
4/a
部分计算为一个整数,当您将其转换为
double
时,它已经被截断。您要做的是
4.0/a
,而不需要显式转换。

代码中的问题是在计算值时:

// PI = 4 - (4/3) + (4/5) - (4/7) ... for 100 first statements
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
    double PI = 0.0;
    int a = 1;
    for (int i = 1; i <= 100; i++) {
        if (i % 2 == 1) {
            PI += double(4 / a);
        }
        else {
            PI -= double(4 / a);
        }
        a += 2;
    }
    cout << "PI Number is : " << PI;
    cout << endl;
    return 0;
}
尝试将
double(4/a)
替换为
4.0/a
double PI = 0.0;
int a = 1;
for (int i = 1; i <= 100; i++) {
    if (i % 2 == 1) {
        PI += double(4 / a);
    }
    else {
        PI -= double(4 / a);
    }
    a += 2;
}
double PI = 0.0;
int a = 1;
for (int i = 1; i <= 100; i++) {
    if (i % 2 == 1) {
        PI += (double)4 / a;
    }
    else {
        PI -= (double)4 / a;
    }
    a += 2;
}