简体   繁体   中英

How to program a loop in python that sums numbers

I am trying to write a loop that calculates the total of the following series of numbers: 1/30 +2/29+3/28+…+30/1. I'm having trouble figuring out how to add, because the program below just displays the total as 0.033333333....

def main():
  A=1
  B=30
  sum=(A/B)
  while A<=30:
      A+=1
      B-=1
  print('Total:',sum)
main()

创建两个所需数字的列表,计算每个分数的值,然后求和。

sum(( a/b for a,b in zip(range(1,31),range(30,0,-1))))

You are not adding anything to sum on each iteration. You must add

sum = sum + A / B

inside the while loop. But you have to initialize sum with zero:

sum = 0

Note:

Don't use sum as name of a variable because it's a built-in function of Python. You can call that variable result , my_sum , ...

Code:

def main():
    A = 1
    B = 30
    result = 0
    while A <= 30:
        print A, B
        result += (A / B)
        A += 1
        B -= 1

    print('Total:', result)
main()

Also:

You can see that in each term of the sum, A + B == 31 , so B == 31 - A . Therefore, the code can be simplified:

def main():
    A = 1
    result = 0
    while A <= 30:
        result += (float(A) / (30 - A + 1))
        A += 1
    print('Total:', result)

You may mean this to be your code:

def main():
    A=1
    B=30
    sume= A/B
    while B>1:
        A+=1
        B-=1
        sume += A/B
    print('Total:',sume)

main()

Moreover, you shouldn't override sum unless you know you are not using it in your program elsewhere. sum is a reserved word in python.

 public class Main {
    public static void 
main(String[] args) {
        int i,j;
        for(i=1;i<=30;i++)
        {
            for( j=30;j>=1;j--)
            i+=i/j;
        }
        System.out.println(i+ " 
");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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