如何在Python中对幂运算结果求和?附现有代码求助
Hey there! Let's fix up your code to get the horizontal output you want, plus add that sum calculation you're after. Let's break this down step by step.
First, let's look at the small tweaks needed in your current code:
- Your print statements are each on a new line instead of a horizontal list. We can fix that with the
end=" "parameter inprint(). - When the power
Bis negative, your loop runs one extra time (e.g., if B=-2, it outputs A^0, A^-1, A^-2 instead of just two terms, matching your positive power example where B=3 gives 3 results). - You don't have a variable tracking the sum of the powers as you calculate them.
Here's a revised version of your code that addresses all these points, plus adds the sum functionality:
# Get input from the user A = float(input("Number:")) B = int(input("Power:")) # Using int makes more sense since we're counting iterations total = 0.0 # Initialize a variable to track the sum print("Result of Powers:", end=" ") if B > 0: # Positive power: iterate from 0 to B-1 (exactly B terms) for i in range(B): val = A ** i print(val, end=" ") total += val elif B < 0: # Negative power: iterate from 0 to B+1 (step -1), exactly abs(B) terms for i in range(0, B, -1): val = A ** i print(val, end=" ") total += val else: # Handle B=0 case: only output A^0 which is 1 val = A ** 0 print(val, end=" ") total += val # Print the sum on a new line for clarity print(f"\nSum of powers: {total}")
Let me walk through the key changes:
- We use
int(input("Power:"))because power values here represent the number of terms (e.g., B=3 means 3 terms: 0,1,2 exponents). Using integers avoids weird floating-point loop behavior. - The
totalvariable starts at 0.0, and we add each calculated power value to it every iteration. - For positive B,
range(B)gives us 0,1,...,B-1 (exactly B terms, matching your example where B=3 outputs 1,2,4). - For negative B,
range(0, B, -1)gives us 0,-1,...,B+1 (exactly abs(B) terms, e.g., B=-2 outputs 1, 0.5). end=" "in the print statements keeps all results on one line, then we print the sum on a new line for readability.
Testing this with your example:
- Input Number:2, Power:3
- Output:
Result of Powers: 1.0 2.0 4.0 - Sum:
Sum of powers: 7.0
If you input Number:2, Power:-2:
- Output:
Result of Powers: 1.0 0.5 - Sum:
Sum of powers: 1.5
That should do exactly what you're looking for! Feel free to ask if you need any more clarification.
内容的提问来源于stack exchange,提问作者Chad Champion_BD
相关产品推荐
相关产品推荐

