牛客网刷题-(10)

2024-01-18 17:48:17 浏览数 (1)

(1)利用循环语句求立方和

代码语言:javascript复制
#1.利用循环语句,求1-100的立方和
sum = 0
i = 0
while i < 101:
    sum  = i**3
    i = i   1
print(sum)
代码语言:javascript复制
#做法2: for 循环
s = 0
for i in range(1,101):
    s = s   i**3
print(s)

(2)求斐波那契数列的第n项值

代码语言:javascript复制
#2. 求第 n 个斐波那契数列的值
a = 1
b = 1
i = 1
n = int(input())
while n > i:
    a,b = b,a b
    n -= 1
print(a)
代码语言:javascript复制
#解法2
n = int(input())
a,b,i = 1,1,1
while i < n:
    a, b = b, a b
    i  = 1
print(a)
代码语言:javascript复制
#解法3
n = int(input())
a,b = 1,1
for i in range(1,n):
    a,b = b,a b
print(a)

因为枚举n项打印的是第n - 1项,所以我们最后print(a)

(3)for 循环遍历每一个字符的方法

代码语言:javascript复制
#方法1:
for c in "python":
    print(c,end=" ")
print()

#方法2:
s = "piggylin"
for c in s:
    print(c,end=" ")

0 人点赞