需要帮忙存储从 while 循环中获取的值。

huangapple go评论71阅读模式
英文:

Need help storing values i get from a while loop

问题

我希望能够存储我从这个 while 循环中获取的数据,这些数据是求和结果,以便我最终可以将它们相加。

public class Sum 
{
    public static void main(String[] args)
    {
        double second = 1;
        double n = 4;
        double start = 1;
        double sum1= 1.0;

         while(second<=n)
        {
            sum1 = start/second;   
            second++;
            System.out.println(sum1);  
        }
    }
}
英文:

I would like to be able to store the data I get which is the sum from this while loop so I can add them together in the end.

public class Sum 
{
    public static void main(String[] args)
    {
        double second = 1;
        double n = 4;
        double start = 1;
        double sum1= 1.0;
    
         while(second&lt;=n)
        {
            sum1 = start/second;   
            second++;
            System.out.println(sum1);  
        }
    }
}

答案1

得分: 1

你可以将值添加到sum1变量中,最后可以获得所有值的总和。

public class Sum 
{
    public static void main(String[] args)
    {
        double second = 1;
        double n = 4;
        double start = 1;
        double sum1 = 0;

        while(second<=n)
        {
            sum1 += start/second;
            second++;
        }
        System.out.println(sum1);
    }
}
英文:

You can add the value to the sum1 variable and at last, you can get the total of all the values.

public class Sum 
{
    public static void main(String[] args)
    {
        double second = 1;
        double n = 4;
        double start = 1;
        double sum1 = 0;

        while(second&lt;=n)
        {
            sum1 += start/second;
            second++;
        }
        System.out.println(sum1);
    }
}

huangapple
  • 本文由 发表于 2020年10月13日 14:59:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64330135.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定