我需要编写一个代码,要求用户输入任何数字的“num”,并计算 1 到 num 范围内所有奇数的总和。我似乎无法弄清楚如何编写此代码,因为我们有一个类似的问题,即在我能够弄清楚的范围内添加偶数。
我还添加了我已经编写的代码行,用于批评我可能做对/错的事情。将不胜感激任何帮助:)
total = 0
for i in range(0, num + 1, 1):
total = total + i
return total
Run Code Online (Sandbox Code Playgroud)
total = sum(range(1, num + 1, 2))
Run Code Online (Sandbox Code Playgroud)
如果你真的需要一个 for 循环:
total = 0
for i in range(1, num+1, 2):
total += i
Run Code Online (Sandbox Code Playgroud)
并使其更具异国情调,您可以考虑i%2==1仅适用于奇数和偶数的属性i%2==0(注意:您使代码不可读)
total = 0
for i in range(1, num+1):
total += i * (i % 2)
Run Code Online (Sandbox Code Playgroud)
通过利用奇偶属性,您可以发明更多方法来解决此问题,例如:
(-1)^i 是 1 或 -1i & 0x1 是 0 或 1abs(((1j)**i).real) 是 0 或 1等等