以正确的格式循环

时间:2019-06-27 17:47:18

标签: java loops increment

我想在50个循环后增加循环结果,改为100。

包括我的代码:

包装近似值;

导入java.util.Scanner;

公共类roxPie {

public static void main(String[] args) {

    //prompts for and saves the number of loops entered
    Scanner myObj = new Scanner(System.in);

    //makes a string called i
    String i;

    double piOver4 = 0;
    double pi;

    //test to see the results under approximation
    double sign = 1; 


    // Enter number of loops 
    System.out.println("Enter maximum loop:");

    //assigns number of loop count to loop function
    i = myObj.nextLine();

    //prints out loop string
    System.out.println("Maximum loop count: " + i);
    System.out.printf("%-20s %-20s %-20s %-20s %-20s\n", "Count", "Approximation", "Error", "Variance (%)", "termI");

    //converts loop string to loop number
    double b = Double.parseDouble(i);


    //for loop using the number of loops entered b = i = scanner = number of loops
    for (int w = 1; w <= b; w++) {

        if (w > 100) {
            w+= 99;
        }

        //calculate term
        double term = (sign/(double) ((2*w)-1));

        //calculate piOver 4
        piOver4 = piOver4 + term;

        //calculating pi
         pi = piOver4 * 4;

        //alternating sign
        sign = sign * -1;

        //calculate error
        double error = pi - Math.PI;

        //calculate variance
        double variance = (error / Math.PI) * 100;

        //display results
        System.out.printf(w + ":" + "%-20s %-20s %-20s %-20s %-20s\n", " ", pi , error, variance, term);

    }
        //display PI
        System.out.println("Math.PI = " + Math.PI + " \n\n");

}

}

我希望它循环播放,例如1776个循环,在50个循环之后,我需要它从50到100到101到200到201递增直到1776。

1 个答案:

答案 0 :(得分:0)

如果涉及复杂的增量逻辑,则可能值得考虑使用while循环,以便可以使用if语句更好地控制它。像这样:

retainInstance = true