223k views
4 votes
Challenge Program (Optional 10 bonus points): Using only the commands we have covered in class so far, write a program that asks a user for a number of digits, and prints the number it (pi) rounded to that many digits of precision. Do NOT use the round () function. Instead, get creative and think of another way! Example output (using input 5): Please enter the number of digits of precision for pi: 5 The value of pi to 5 digits is: 3.14159 If you complete this challenge correctly, you will receive 10 bonus points on this assignment. Please name your program Lab3b_challenge.py and submit with the rest of your files.

1 Answer

7 votes

One way to achieve rounding without using the round() function is by manipulating the number to include only the desired number of digits after the decimal point.

# Function to round pi to the specified number of digits

def round_pi_to_precision(digits):

# Calculate pi with extra precision

pi_with_extra_precision = math.pi * (10 ** (digits + 1))

# Truncate the extra precision

truncated_pi = int(pi_with_extra_precision)

# Divide by 10 to shift the decimal point back

rounded_pi = truncated_pi / (10 ** digits)

return rounded_pi

# Get user input for the number of digits

num_digits = int(input("Please enter the number of digits of precision for pi: "))

# Validate input

if num_digits < 0:

print("Please enter a non-negative number.")

else:

# Calculate and print the rounded value of pi

result = round_pi_to_precision(num_digits)

print(f"The value of pi to {num_digits} digits is: {result}")

User Jared Forsyth
by
8.4k points

No related questions found