Computing issue in writing program
I'm trying to write a quick test program that would add two number inclusively, let say one integer is 2 and the other is 7, I want it to comp开发者_运维技巧ute like this (2+3+4+5+6+7=27). Can't wrap my head around it.
Here is what I have
public class Test
{
public static void main (String[] args)
{
int lo=2;
int hi=7;
int result=0;
for(int i=lo;i<=hi;i++)
result=i+i;
System.out.println(result);
}
}
You were close. I think you mean
result = result + i;
This basically means take the current value of result
, add i
to it, and then make result
equal to that sum. This has the overall effect of adding i
to result
.
There's also a short-hand for _something_ = _something_ + _otherThing_
, which in this case would look like:
result += i;
Use some math:
Sn = n/2 * (A1 + An),
where Sn is the sum of arithmetic progression of n elements with A1 as first element and An as last. See here.
精彩评论