简体   繁体   中英

How do I apply a mathematical equation to each number in a for loop?

I've done some searching around and tried some solutions I've found, but a lot of them result in the same problem I am having. I'd like to apply a mathematical equation to each number of a for loop. The problem I am having is that the equation only occurs on the last number in that for loop. For example:

for (int i = 3; i <= 5; i++)
{
    radius = i;
    area = (Math.PI * (radius * radius));
    System.out.println (radius)
}

My code is much more extensive than this, but this is the part I am having issues with. It prints:

3
4
5
Radius: 5
Area: 78.53981633974483

I tried using for each loop, while loop, putting the numbers in a variable to pull from, I'm kind of at my wits end on what to try myself without asking. I'd like the for loop to look like:

3
Radius: 3
Area: //... the area with radius 3...
4
Radius: 4
Area: //... the area with radius 4...
5
Radius: 5
Area: //...area with radius 5...

How would I go about going through each iteration of the for loop and apply the mathematical equation to it?

You did not post the full code, but from your output one can guess you have something like this:

int radius = 0;
double area = 0.0;
for (int i = 3; i <= 5; i++)
{
    radius = i;
    area = (Math.PI * (radius * radius));
    System.out.println (radius)
}
System.out.println("Radius: " + radius);
System.out.println("Area: " + area);

With that your program loops over i = 3, 4, 5; for each i it calculates the area and prints the radius. Only when the loop is over it prints radius and area - and exactly that is what you see in the output.

Change your code as commented by Federico to look like this:

int radius = 0;
double area = 0.0;
for (int i = 3; i <= 5; i++)
{
    radius = i;
    area = (Math.PI * (radius * radius));
    System.out.println("Radius: " + radius);
    System.out.println("Area: " + area);
}

Then it will loop over the same values, and for each perform the calculation and print the result.

Assuming you are using java 8, take advantage of it.

IntStream
    .range(3, 6)
    .forEach(radius -> {
        float area = (float) (Math.PI * (radius * radius));
        System.out.println("Radius: " + radius);
        System.out.println("Area: " + area);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM