0

Hello I'm a beginner in Java and I have a question regarding summing the iterations. The question is: Write a program that computes the following expression to 4 decimal places: (1/10) + (2/9) + (3/8) + (4/7) + (5/6) + (6/5) + (7/4) + (8/3) + (9/2) + (10/1)

So far I have:

public class Expression
{
    public static void main(String[] args)
    {
        float x;
        for ( float m=1, n=10; m<11; m++,n--)
        {
            x = (m)/(n);
        }

How would I go about summing all the iterations the for loop makes?

Thanks everyone :)

4

4 回答 4

2
public class Expression
{
    public static void main(String[] args)
    {
        float x = 0;
        for ( float m=1, n=10; m<11; m++,n--)
        {
            x += (m)/(n);
        }
    System.out.println(x);
    }
}
于 2013-09-09T23:19:48.830 回答
1

不错的代码,到目前为止我喜欢它!

您需要一个变量,例如:sum = sum + x;或更短sum += x;的循环内。float sum = 0;在循环之前定义它。

也可以直接用x,用0定义,但是编译器无论如何都会优化,所以没有速度增益。

于 2013-09-09T23:19:14.183 回答
1

+=运营商 。x += y相当于x = x + y。在您的情况下,您将拥有x += (m)/(n),最终导致:

public class Expression {
  public static void main(String[] args) {           
    float x = 0;

    for ( float m=1, n=10; m<11; m++,n--) {
      x += (m)/(n);
    }
  }
}
于 2013-09-09T23:19:23.853 回答
1

改变

 x = (m)/(n);

x += (m)/(n);

由于x已经在循环之外的范围内,因此可以这样做,并且x将在迭代之间持续存在。但是,我建议更改循环:

float x=0;
for ( float m=1; m<11; m++)
  {
     x += (m)/(11-m);
  }

将来可能会更直接地阅读。

于 2013-09-09T23:19:40.263 回答