Greatest common divisor, least common multiple, hundred money white chicken, output isosceles triangle exercises in Python

#1.分别用for循环和while语句计算S=1+2+3+...+100的值
'''S=0
for i in range(1,101):
    S+=i
print("S=",S)'''

'''i=1
S=0
while i<=100:
    S+=i
    i+=1
print("S=",S)'''

#计算1-100内偶数的和
i=1
S=0
while i<=100:
    if i%2==0:
        S += i
    i+=1
print("S=",S)
#计算1-100内奇数的和
i=1
S=0
while i<=100:
    if i%2!=0:
        S += i
    i+=1
print("S=",S)
#2.求 1000 以内的所有能被3和7整除的数之和
'''S=0
for i in range(1,1001):
    if i%21==0:
        S+=i
print("S=",S)'''
#用while循环
i=1
S=0
while i<=1000:
    if i%21==0:
        S+=i
    i+=1
print("S=",S)

#3.使用for循环打印一个等腰三角型。
x=eval(input("请输入等腰三角形的层数:"))
for i in range(1,x+1):#等腰三角形
        for j in range(1,x+1-i):
            print(' ',end=' ')
        for k in range(2*i-1):
            print('*',end=' ')
        print()
		
#4.编程解决百钱买百鸡的数学问题
for x in range(0,21):
    for z in range(3,100):
        y=100-x-z
        if 5*x+3*y+z/3==100 and x>=0 and y>=0 and z>=0:
            print("公鸡:",x,"母鸡:",y,"鸡雏:",z)

#5.使用break和continue语句改写九九乘法口诀
for x in range(1,10):
    for y in range(1,10):
        if y<=x:
            print(y,"*",x,"=",x*y," ",end="")
        else:
            continue
    print("")

#6.改进对鸡兔同笼问题:输入任意组数据,求出鸡兔同笼
for i in range(1,101):
    print("欢迎来到鸡兔同笼问题解答器:(你有100次机会)")
    h=int(input("请输入头的数量:"))
    f=int(input("请输入脚的数量:"))
    # 这里将鸡和兔子数量int是为了不想输出的数值是浮点数
    # y=int((f-2*h)/2)
    # x=int(h-y)
    y=(f-2*h)/2
    x=h-y
    if x>=0 and y>=0 and int(x)==x and int(y)==y:
        # 想到了一个更好的方法控制输出数为整数(而不是浮点数)
        y=int(y)
        x=int(x)
        print("鸡的数目为:",x,"兔的数目为:",y)
    else:
        print("你的输入有误,请重新输入!")

# 7.求最大公约数计算。即从键盘上输入两个整数,编写程序,计算两个数的最大公约数和最小公倍数。
#辗转相除法(最大公约数*最大公约数=a*b)
for i in range(1,101):
    a=eval(input("请输入任意一个整数:"))
    b=eval(input("请输入任意第二个整数:"))
    temp=0
    x=a
    y=b
    if(a<b):
        (a,b)=(b,a)
        while a%b!=0:
            temp=a%b
            a=b
            b=temp
    print("最大公约数:",b)
    print("最小公倍数:",int(x*y/b))

Guess you like

Origin blog.csdn.net/m0_52646273/article/details/115133128