编写接收用户温度输入并给出外套穿着分级建议的算法
Temperature-Based Outerwear Recommendation Algorithm
Hey there! Let's build a simple, reliable algorithm that gives outerwear suggestions based on the temperature a user inputs. Here's a step-by-step breakdown and implementation:
Core Rules Recap
First, let's lock in the requirements to avoid any edge case confusion:
- When the temperature is below 32°F, recommend a heavy coat
- When the temperature is between 32°F and 50°F (inclusive), recommend a light jacket
- When the temperature is above 50°F, let the user know they don't need an outer layer
Python Implementation
Here's a clean, user-friendly function that follows these rules perfectly:
def get_outerwear_recommendation(temperature): # Check for heavy coat condition first if temperature < 32: return "建议携带厚外套" # Then cover the light jacket range (includes boundary values) elif 32 <= temperature <= 50: return "建议携带薄外套" # All remaining cases are temperatures above 50 else: return "建议无需外套" # Example of how to run this with user input if __name__ == "__main__": try: user_temperature = float(input("请输入当前温度:")) print(get_outerwear_recommendation(user_temperature)) except ValueError: print("请输入有效的数字温度值哦!")
Quick Notes
- We added basic error handling to catch non-numeric inputs, making the algorithm more robust for real-world use
- The conditional checks strictly follow your specified rules, including correctly handling the boundary temperatures (32 and 50)
- This logic is super easy to adapt to other languages (like JavaScript, Java, etc.)—just replicate the temperature range checks in your preferred syntax
内容的提问来源于stack exchange,提问作者Francis Akujobi
相关产品推荐
相关产品推荐

