【问题标题】:WAP that takes an integer N from keyboard, computes and display the sum of the numbers from N to (2*N) if N is nonnegative. If N is negative then [closed]WAP 从键盘获取整数 N,如果 N 为非负数,则计算并显示从 N 到 (2*N) 的数字之和。如果 N 为负数,则 [关闭]
【发布时间】:2021-07-09 03:23:57
【问题描述】:

WAP 从键盘读取整数 N,如果 N 为非负数,则计算并显示从 N 到 (2N) 的数字之和。如果 N 是负数,则它是从 (2n) 到 n 的数之和。起点和终点都包含在总和中。

【问题讨论】:

  • 答案 n=int(input("输入一个整数:")) m=0 if (n>-1): for i in range (n,2*n+1): m+ =i else: for i in range (2*n,n+1): m+=i print(m)
  • 问题不清楚。什么是 WAP?是来自computertutor.in/resources/…吗?如果是这样,为什么要在这里问并自己给出答案?
  • 不,它不是来自那里,但感谢您的告知,WAP 正在编写程序

标签: python machine-learning artificial-intelligence


【解决方案1】:
def myfunc(n):
ls=[]

#we are going to append all the number from n to 2n
#and return their sum
#since 2n is also included, therefore end point of loop must be 2n+1

if n<0:
    for i in range(n,2*n-1,-1):
       ls.append(i)
else:
    for i in range (n,2*n+1):
        ls.append(i)
return sum(ls)

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 2019-10-15
    • 1970-01-01
    • 2011-11-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 2021-12-01
    • 1970-01-01
    相关资源
    最近更新 更多