代码如下:
#include <iostream>
#include <string>
#include <cstdlib> // 用于将字符串转换为浮点数
using namespace std;
int main() {
string input_str;
cout << "需转换的温度为: ";
getline(cin, input_str);
string temp_value = input_str.substr(0, input_str.length() - 1);
char temp_system = input_str[input_str.length() - 1];
if (temp_system == 'C') {
double value = atof(temp_value.c_str());
int converted_temp = static_cast<int>(value * 1.8 + 32);
cout << "转换后的温度为" << converted_temp << "F" << endl;
}
else if (temp_system == 'F') {
double value = atof(temp_value.c_str());
int converted_temp = static_cast<int>((value - 32) / 1.8);
cout << "转换后的温度为" << converted_temp << "C" << endl;
}
else {
cout << "输入格式错误" <<endl;
}
return 0;
}
这段 C++ 代码实现温度单位转换,步骤如下:
- 引入头文件:包含输入输出、字符串处理、字符串转浮点数所需头文件。
- 使用命名空间:
using namespace std;
让代码可直接用std
里的标识符。- 主函数:
- 定义
string
变量接收用户输入的温度值和单位。- 提取温度数值和单位。
- 根据单位进行转换:
- 若单位为
C
,按公式转华氏度输出。- 若单位为
F
,按公式转摄氏度输出。- 其他情况输出错误提示。
- 返回 0:表示程序正常结束 。
注意:
此代码中的单位C和F均为大写,若输入为小写则会提示输出错误。
觉得有帮助就给博主点个关注叭~~
有问题的可以私信或者在评论区一起交流
友友们一起加油叭QAQ