为什么在尝试获得n个自然数的总和时会继续返回1?

发布于 2025-01-25 04:12:29 字数 1488 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尘曦 2025-02-01 04:12:29

尝试返回ttl(您可能需要考虑重命名ttl to Total两个额外的字符大大增加了可读性),并且包括最后一个1

--- before/before.py
+++ after/after.py
@@ -1,8 +1,8 @@
def summation(n):
     ttl = 0
-    while n != 1:
+    while n >= 1:
         ttl = ttl + n
         n = n - 1
-    return 1
+    return ttl

print(summation(5))

输出:

15

Try returning ttl (you might want to consider renaming ttl to total the two extra characters increase readability a lot), and including the last 1:

--- before/before.py
+++ after/after.py
@@ -1,8 +1,8 @@
def summation(n):
     ttl = 0
-    while n != 1:
+    while n >= 1:
         ttl = ttl + n
         n = n - 1
-    return 1
+    return ttl

print(summation(5))

Output:

15
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文