You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无第三方库实现几何均值算法: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 True loop just keeps reusing the same n value 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 = -1 leads to division by zero (if you enter one valid number then 0) or incorrect exponentiation (if you enter 0 first). Also, the return statement references suma, 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_count to detect if 0 was the first input, and throws the required error.
  • Safe calculation: valid_count starts 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-except block 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:18:49