无第三方库实现几何均值算法:Python程序无返回结果求助
Fixing Your Geometric Mean Calculator
Let's walk through the issues in your current code and fix them to meet your requirements:
Key Problems in the Original Code
- Stuck in a loop with no new input: You only read the user's input once at the start of the function. After that, the
while Trueloop just keeps reusing the samenvalue forever (unless it was 0 initially), so you never get to enter additional numbers. - No negative number check: Your code doesn't validate if the input is negative, which violates the requirement to error on negative inputs.
- First input 0 doesn't error: If you enter 0 right away, the code just breaks the loop and tries to calculate the mean instead of throwing an error like it should.
- Broken calculation logic: The initial value of
i = -1leads to division by zero (if you enter one valid number then 0) or incorrect exponentiation (if you enter 0 first). Also, the return statement referencessuma, a variable that doesn't even exist.
Fixed Code
def calculate_geometric_mean(): product = 1 valid_count = 0 # Tracks how many positive numbers we've received while True: # Handle non-integer inputs gracefully try: num = int(input("Give a number: ")) except ValueError: print("Error: Please enter a valid whole number.") continue # Check for negative numbers first if num < 0: print("Error: Negative numbers are not allowed.") return # Handle 0 input if num == 0: if valid_count == 0: # First input was 0 - trigger error print("Error: Cannot start the sequence with 0.") return else: # End the sequence and calculate the mean break # Process valid positive number product *= num valid_count += 1 # Calculate and display the geometric mean geometric_mean = product ** (1 / valid_count) print(f"Geometric mean of the sequence: {geometric_mean}") return valid_count, product # Run the function calculate_geometric_mean()
What Changed:
- Continuous input handling: The input is read inside the loop, so you can enter multiple numbers until you type 0.
- Negative input validation: Immediately errors and exits if a negative number is entered.
- First 0 check: Uses
valid_countto detect if 0 was the first input, and throws the required error. - Safe calculation:
valid_countstarts at 0 and only increments for valid numbers, so we never divide by zero when computing the mean (since we only calculate it after at least one valid input). - Error handling for non-integers: Added a
try-exceptblock to catch cases where the user enters something that's not a number. - Valid return value: Returns the count of valid numbers and their product (no undefined variables anymore).
内容的提问来源于stack exchange,提问作者stickyjack
相关产品推荐
相关产品推荐

