java for loop sum和range of range

时间:2015-10-03 08:41:32

标签: java

我已经计算了for循环范围的总和,但是我不知道如何计算并为我的解决方案做平均值。 必须在没有任何ifs的情况下完成。只是For循环:

//defining the variables
        // Constants & Variables here
int i;
int numStart;
int numEnd;
double sum = 0;
double average=0;
double loopCount=0;
System.out.print("Enter Start number: "); // keep print line open
numStart = console.nextInt();

System.out.print("Enter End number: ");
numEnd = console.nextInt();

        //enter thevalue
        for (i = numStart; i <= numEnd; i++ )
        {
            sum = sum + i;
            loopCount = numEnd - numStart;
            average = sum+1 / i;


        }
        System.out.println();
        System.out.println( "Sum is: " + sum);
        System.out.println();
        System.out.println( "Average is: " + average);
        System.out.println();

3 个答案:

答案 0 :(得分:3)

为什么甚至使用for - 循环。感谢高斯,我们知道范围[1 , n]中所有元素的总和为n * (n + 1) / 2。范围内的整数数量仅为numEnd - numStart + 1,平均值是范围内所有整数的总和除以范围内的整数数。

所以优化的解决方案看起来像这样:

...
//got numStart and numEnd
int sum = numEnd * (numEnd + 1) / 2 - (numStart - 1) * numStart / 2;
int count = numEnd - numStart + 1;
average = sum / count;

答案 1 :(得分:0)

    for (i = numStart; i <= numEnd; i++ )
    {
        sum = sum + i;
        loopcount++;
    }
    average = sum / loopcount;

答案 2 :(得分:0)

你可以这样做:

for (i = numStart; i <= numEnd; i++ )
                    {
                        sum = sum + i;
                        loopCount = numEnd - numStart;
                        average = sum /(loopCount+1);


                    }

for (i = numStart; i <= numEnd; i++ )
                {
                    sum = sum + i;
                    loopcount++;
                }
                average = sum / loopcount;