简体   繁体   English

如何将数学方程应用于 for 循环中的每个数字?

[英]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.我想对 for 循环的每个数字应用一个数学方程。 The problem I am having is that the equation only occurs on the last number in that for loop.我遇到的问题是该等式仅出现在该 for 循环中的最后一个数字上。 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.我尝试使用for每个循环,while循环,将数字放入一个变量中以从中提取,我有点不知所措,不问自己要尝试什么。 I'd like the for loop to look like:我希望 for 循环看起来像:

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?我将如何 go 经历 for 循环的每次迭代并将数学方程应用于它?

You did not post the full code, but from your output one can guess you have something like this:您没有发布完整的代码,但从您的 output 可以猜到您有这样的事情:

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;这样你的程序就会循环 i = 3, 4, 5; for each i it calculates the area and prints the radius.对于每个 i 它计算面积并打印半径。 Only when the loop is over it prints radius and area - and exactly that is what you see in the output.只有当循环结束时,它才会打印半径和面积 - 这正是您在 output 中看到的内容。

Change your code as commented by Federico to look like this:将 Federico 评论的代码更改为如下所示:

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.假设您使用的是 java 8,请利用它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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