|
|
|
描述 设计一个自动转化温度的程序,能够根据输入的温度单位(C/F)和数值进行温度转换,温度单位不区分大小写(C、c、F、f),当输入的是无效字符时,输出无效的温度单位,请使用C或F。华氏度与摄氏度转换关系如下:

输入描述 输入温度数据(格式:数字+单位,如32F或20C)
输出描述 输出温度转换的结果
用例输入 1 [color=rgb(48, 145, 242) !important][url=][/url] 32F
用例输出 1 [color=rgb(48, 145, 242) !important][url=][/url] 32°F = 0°C
答案
#include <iostream>
using namespace std;
int main() {
// 显示程序标题
cout << "";
// 变量定义
double temperature;
char unit;
// 获取输入
cout << "";
cin >> temperature >> unit;
// 执行转换
if (unit == 'C' || unit == 'c') {
// 摄氏度转华氏度
double fahrenheit = temperature * 9.0 / 5.0 + 32;
cout << temperature << "°C = " << fahrenheit << "°F\n";
}
else if (unit == 'F' || unit == 'f') {
// 华氏度转摄氏度
double celsius = (temperature - 32) * 5.0 / 9.0;
cout << temperature << "°F = " << celsius << "°C\n";
}
else {
// 无效单位处理
cout << "错误:无效的温度单位,请使用 C 或 F!\n";
}
return 0;
}
|
|