如何在循环中保存函数数据以实现向量计算器的分量求和?
Hey there! I see you want to keep track of all the vector components you input so you can sum them up later. Let's fix this step by step, and also correct a couple of small bugs in your code that might throw off your calculations.
Core Idea
Use lists to store each round's calculated X and Y components. Lists let you dynamically add new values as you go, and Python's built-in sum() function makes it easy to calculate the total later.
Modified Code with Explanations
Here's your updated code with all the necessary changes:
import math import os # Added this since you're using os.system("cls") from ctypes import * STD_OUTPUT_HANDLE = -11 class COORD (Structure): pass COORD._fields_=[("X",c_short),("Y",c_short)] def print_at(r, c, s): h = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE) windll.kernel32.SetConsoleCursorPosition(h, COORD(c, r)) c = s.encode("windows-1252") windll.kernel32.WriteConsoleA(h, c_char_p(c), len(c), None, None) def Compute(Force, Angle, Direction): # Fixed: Pass parameters instead of using global variables (better practice) # Critical fix: math.cos/sin require radians, not degrees! Converted Angle with math.radians() if Direction in ["NofE", "NofW", "SofW", "SofE"]: xComp1 = round(Force * math.cos(math.radians(Angle)), 3) yComp1 = round(Force * math.sin(math.radians(Angle)), 3) elif Direction in ["EofN", "WofN", "WofS", "EofS"]: yComp1 = round(Force * math.cos(math.radians(Angle)), 3) xComp1 = round(Force * math.sin(math.radians(Angle)), 3) else: # Added fallback for invalid directions xComp1 = 0.0 yComp1 = 0.0 print_at(4, 95, "Invalid Dir") print_at(4, 110, "Invalid Dir") print_at(4, 95, str(xComp1)) print_at(4, 110, str(yComp1)) # Fixed: Changed print() to print_at() return xComp1, yComp1 # Return components to store in lists ## main program ## x_components = [] # List to track all X components y_components = [] # List to track all Y components while True: _=os.system("cls") print_at(1, 0, "Directions: NofE, NofW, SofW, SofE, EofN, WofN, WofS, EofS \n") print_at(3, 55, "Magnitude") print_at(3, 70, "Direction") print_at(3, 85, "Angle") print_at(3, 95, "X-Component") print_at(3, 110, "Y-Component \n") Force = float(input("\n Force: ")) print_at(4, 55, str(Force)) if Force == 0: break Angle = float(input("\n Angle: ")) print_at(4, 85, str(Angle)) Direction = input("\n Direction: ").strip() print_at(4, 70, str(Direction)) # Store the computed components in our lists x_comp, y_comp = Compute(Force, Angle, Direction) x_components.append(x_comp) y_components.append(y_comp) Continue = input("\n Do you want to continue?(Y/N)").strip() if Continue.lower() == "y": continue elif Continue.lower() == "n": break else: print ("Answer not recognized. Exiting...") break # Calculate and display totals after exiting the loop total_x = sum(x_components) total_y = sum(y_components) print_at(6, 0, f"=== Total Vector Sum ===") print_at(7, 0, f"Total X-Component: {round(total_x, 3)}") print_at(8, 0, f"Total Y-Component: {round(total_y, 3)}") # Optional: Calculate resultant magnitude and direction resultant_magnitude = round(math.hypot(total_x, total_y), 3) if total_x == 0 and total_y == 0: resultant_direction = "Zero vector (no direction)" else: resultant_angle = round(math.degrees(math.atan2(total_y, total_x)), 3) resultant_direction = f"{resultant_angle}° from positive X-axis" print_at(9, 0, f"Resultant Magnitude: {resultant_magnitude}") print_at(10, 0, f"Resultant Direction: {resultant_direction}")
Key Changes Made:
- Added lists for tracking components:
x_componentsandy_componentsstore every calculated vector component. - Fixed calculation bug: Your original code used
math.degrees()on the cos/sin results, which is backwards—math.cos()expects radians, so we convert the input angle withmath.radians()instead. - Improved
Computefunction: Now accepts parameters (no more global variables) and returns the components so we can store them. - Fixed output typo: Changed
print(4, 110, ...)toprint_at(4, 110, ...)so the Y-component displays correctly. - Added sum calculation: After exiting the loop, we calculate the total X/Y components and even the resultant vector's magnitude/direction for extra utility.
How It Works:
Every time you input a vector and compute its components, those values get added to the x_components and y_components lists. When you exit the loop (either by entering Force=0 or choosing "N"), the code sums all the values in the lists and displays the total, plus the resultant vector info if you want it.
内容的提问来源于stack exchange,提问作者Miles

