2016-09-16 2 views
1

私はC++を初めて使いました。問題がどこにあるのか分かりません。私はGregory-Leibnizシリーズを使ってpiをどれだけ探したいのかユーザーに尋ねようとしていますが、数字を入力するたびに常にループから1をとります。事前のおかげで:)Gregory-Leibnizシリーズでpiの価値を見つけるのに問題がある

#include <iostream> 
#include <cmath> 
#include <iomanip> 

using namespace std; 

int main() 
{ 
double x = 0; 
double doubleTerms = 0; 
cout << "How many terms of pi do you want?" << endl; 
cin >> doubleTerms; 

cout << "Thanks the amount of terms you want for pi is: " << doubleTerms << endl; 
//n is the value for where each number is 
//z is to change the number into a negative 
//x is to add up into the total value 
for(int n = 0; n < doubleTerms; n++) 
{ 
    double z = 1/(2 * n + 1); 

    if((n % 2) == 1) 
    { 
     z = z * -1; 
    } 

    x = (x + z); 
} 
double finalValue = 4 * x; 
cout << "The number is: " << finalValue << endl; 


system("pause"); 
return 0; 
} 
+0

あなたの部門に関してこれを確認することができます:http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c – Hayt

+0

提案として、より効率的で非常にシンプルなシリーズ、Nilakanthaシリーズ。 –

答えて

3

1/(2 * n + 1);整数演算に実行されるので、任意の小数部を切り捨てています。

一つの修正ではなく1.0/(2 * n + 1);を書くことである。そして、その用語が原因型プロモーションのルールに浮動小数点に評価されます。

関連する問題