java计算pi,计算Pi Java程序

I'm taking my first Java programming class and this is my first class project. I'm so confused about how to approach it. Any help or correction will be appreciated.

You can approximate the value of the constant PI by using the following series:

PI = 4 ( 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... + ( (-1)^(i+1) )/ (2i - 1) )

Prompt the user for the value of i (in other words, how many terms in this series to use) to

calculate PI. For example, if the user enters 10000, sum the first 10,000 elements of the series and then display the result.

In addition to displaying the final result (your final approximation of PI), I want you to display along the way your intermediate calculates at every power of 10. So 10, 100, 1000, 10000 and so on, display to the screen the approximation of PI at that number of summed elements.

This is what i did so far ..

import java.util.Scanner;

public class CalculatePI {

public static void main(String[] args) {

// Create a Scanner object

Scanner input = new Scanner (System.in);

// Prompt the user to enter input

System.out.println("Enter number of terms");

double i = input.nextDouble(); // value of i user entered

double sum = 0;

for(i=0; i<10000; i++){

if(i%2 == 0) // if the remainder of `i/2` is 0

sum += -1 / ( 2 * i - 1);

else

sum += 1 / (2 * i - 1);

}

System.out.println(sum);

}

}

解决方案

First thing I see is you attempting to return a value from your void main method.

don't return pi; from your main method. Print it.

System.out.println(pi);

Secondly, when people write a for loop, they're commonly iterating over i, which is probably the same i that your professor referred to in the formula

for(double i=0; i

{

sum += ((-1)^(i+1)) / (2 * i - 1) );

}

now, that won't work correctly as is, you still have to handle the ^, which java doesn't use natively. luckily for you, -1^(i+1) is an alternating number, so you can just use an if statement

for(double i=0; i

{

if(i%2 == 0) // if the remainder of `i/2` is 0

sum += -1 / ( 2 * i - 1);

else

sum += 1 / (2 * i - 1);

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值