46.9k views
4 votes
Write a program called nearest_multiple.py that asks the user to input a number (here I will call it num) and a strictly positive integer (here I will call it mult) and prints as output the closest integer to num that is a multiple of mult

1 Answer

5 votes

Answer:

The program is as follows:

num = float(input("Enter a decimal (float): "))

mult = int(input("Enter a positive whole (int): "))

small = (num // mult) * mult

big = small + mult

print(num,"rounded to the nearest multiple of ",mult,"is",end=" ")

print(big if num - small > big - num else small)

Step-by-step explanation:

This gets input for num

num = float(input("Enter a decimal (float): "))

This gets input for mult

mult = int(input("Enter a positive whole (int): "))

This calculates the smaller multiple

small = (num // mult) * mult

This calculates the larger multiple

big = small + mult

This prints the output header

print(num,"rounded to the nearest multiple of ",mult,"is",end=" ")

This prints small if small is closer to num, else it prints big

print(big if num - small > big - num else small)

User Quinestor
by
5.5k points