L1-004. 计算摄氏温度

本文介绍了一个简单的C++程序,用于将华氏温度转换为摄氏温度。该程序利用了基本的输入输出流,并通过公式计算实现温度单位间的转换。


//AC

#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
typedef long long ll;
using namespace std;
int main(){
    double F;
    int C;
    cin>>F;
    C = 5*(F-32)/9;
    printf("Celsius = %d\n",C);
       return 0;
}







### 使用Python编写程序来转换或计算摄氏温度 为了实现从华氏温度到摄氏温度的转换,可以依据转换公式 \( C = (F - 32) \div 1.8 \)[^1]。下面是一个简单的 Python 函数示例,该函数接收一个表示华氏温度的数值作为参数,并返回经过四舍五入处理至小数点后一位的小数形式的摄氏温度。 ```python def fahrenheit_to_celsius(fahrenheit): celsius = (fahrenheit - 32) / 1.8 return round(celsius, 1) # 测试代码片段 if __name__ == "__main__": test_fahrenheit_values = [32, 212, -40, 98.6] for value in test_fahrenheit_values: print(f"{value}°F is {fahrenheit_to_celsius(value)}°C") ``` 此段代码定义了一个名为 `fahrenheit_to_celsius` 的函数用于完成上述功能。此外,在主程序部分提供了一些测试数据以验证函数的工作情况。 对于更复杂的场景下,比如需要支持双向转换(即既可以从华氏转摄氏也可以反过来),以及能够识别用户输入并据此决定调用哪个方向的转换逻辑,则可参照另一种方法: ```python def convert_temperature(temp_str): try: temp_value = float(temp_str[:-1]) # 去掉最后一位单位字母 if temp_str.endswith('F') or temp_str.endswith('f'): converted_temp = (temp_value - 32) * 5 / 9 result_unit = 'C' elif temp_str.endswith('C') or temp_str.endswith('c'): converted_temp = temp_value * 9 / 5 + 32 result_unit = 'F' else: raise ValueError("Invalid temperature unit") formatted_result = f"{round(converted_temp, 1)}{result_unit}" return formatted_result except Exception as e: return "错误!!!你输错了,请重新输入" # 测试代码片段 test_cases = ["32F", "-40C", "invalid_input"] for case in test_cases: print(f"Input: {case}, Output: {convert_temperature(case)}") ``` 这段扩展版本不仅实现了基本的功能需求,还增加了对不同输入格式的支持和异常处理机制,使得整个应用更加健壮可靠[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值