1.读取整数序列,找出他们中的最大值,并计算出它出现的次数
代码:
num_max = 0 num_count = 0 ls = [] while True: ls.append(int(input("请输入一个整数:"))) if len(ls) == 1: num_max = ls[0] num_count = 1 elif ls[len(ls) - 1] != 0: if ls[len(ls) - 1] > num_max: num_max = ls[len(ls) - 1] num_count = 1 elif ls[len(ls) - 1] == num_max: i = 0 num_count = 0 while i < len(ls): if ls[i] == num_max: num_count += 1 i += 1 elif ls[len(ls) - 1] == 0: break print("最大值为{},这个数字出现了{}次".format(num_max, num_count))
验证:
代码:
import random x_min, x_max = -1, 1 y_min, y_max = -1, 1 frequency = int(input("请输入次数:")) i = 0 odd = 0 while i < frequency: x = random.uniform(x_min, x_max) y = random.uniform(y_min, y_max) if x < 0 or ((x + y < 1) and x > 0 and y > 0): odd += 1 i += 1 probability = odd / frequency print("落在奇数区域里的概率为{}".format(probability))
验证:
3.显示21世纪(2001-2100)所有闰年,每行10个,以1个空格隔开
代码:
count = 0 for i in range(2001, 2101): if (i % 4 == 0 and i % 100 != 0) or i % 400 == 0: if count == 9: print(f"{i}") count = 0 elif count < 9: print(f"{i}", end=" ") count += 1
验证:
代码:
def reverse_num(nums): x = str(nums) j = "" for i in range(len(x)): j = x[i] + j i += 1 return j positive_num = int(input("请输入一个整数:")) mun = reverse_num(positive_num) print("这个整数反向输出为:{}".format(mun))
验证:
代码:
def celsius_to_fahrenheit(celsius): fahrenheit = (9 / 5) * celsius + 32 return fahrenheit def fahrenheit_to_celsius(fahrenheit): celsius = (5 / 9) * (fahrenheit - 32) return celsius Celsius = float(input("请输入一个摄氏温度:")) Fahrenheit = float(input("请输入一个华氏温度:")) print("这个摄氏温度{}转化为华氏温度为{}".format(Celsius, celsius_to_fahrenheit(Celsius))) print("这个华氏温度{}转化为摄氏温度为{}".format(Fahrenheit, fahrenheit_to_celsius(Fahrenheit)))
验证:
代码:
def sum_of_sequence(i): j = 0 for x in range(1, i + 1): j = x / (x + 1) + j x += 1 return j nums = int(input("请输入一个正整数:")) print("这个数列的和为{}".format(sum_of_sequence(nums)))
验证:
7.输入三角形的三边长,有效计算面积,无效显示输入无效(两个函数)
代码:
import math def isvalid(side1, side2, side3): if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2 and side1 - side2 < side3 and side2 - side3 < side1 and side1 - side3 < side2: area(side1, side2, side3) else: print("输入无效!!!") def area(side1, side2, side3): p = (side1 + side2 + side3) / 2 triangle_area = math.sqrt(p * (p - side1) * (p - side2) * (p - side3)) print("三角形的面积为{}".format(triangle_area)) triangle_side1 = int(input("请输入第一条边长:")) triangle_side2 = int(input("请输入第一条边长:")) triangle_side3 = int(input("请输入第一条边长:")) isvalid(triangle_side1, triangle_side2, triangle_side3)
验证:
有效输入:
8.梅森素数
代码:
def mersenne_prime(i): for count in range(1, i + 1): num = 2 ** count - 1 if num > 1: flag = True for j in range(2, num // 2 + 1): if num % j == 0: flag = False break if flag: print("p({}) = {} 是梅森素数".format(count, num)) nums = int(input("请输入一个正整数:")) mersenne_prime(nums)
验证: