gpt4 book ai didi

C++ 摄氏转华氏 3 次

转载 作者:行者123 更新时间:2023-11-28 06:42:48 34 4
gpt4 key购买 nike

我正在学习 C++,为此我给自己创造了一个问题,即在控制台中将摄氏度转换为华氏度 3 次。用户将输入摄氏度。我还希望输出显示如下:

摄氏度:华氏度:
cel1 fahr1
cel2 fahr2
cel3 fahr3

到目前为止我尝试过的代码是:

double cel1, cel2, cel3;
double fahr1, fahr2, fahr3;

cout << "Celsius degree one: ";
cin >> cel1;

cout << "Celsius degree two: ";
cin >> cel2;

cout << "Celsius degree three: ";
cin >> cel3;

fahr1 = (cel1 * 9) / 5 + 32;
fahr2 = (cel2 * 9) / 5 + 32;
fahr3 = (cel3 * 9) / 5 + 32;

// messy like this to display like I want to
cout << endl <<
"Celsius: " << "Fahrenheit:" << endl <<
cel1 << " " << fahr1 << endl <<
cel2 << " " << fahr2 << endl <<
cel3 << " " << fahr3 << endl << endl;

它会像我想要的那样显示,但我觉得这可以通过更简单的方式实现,所以我尝试了类似这样的循环,但我不知道如何正确地做到这一点:

double celsius;

for (int times = 0; times != 3; ++times){

cout << "Celsius degree: ";
cin >> celsius;

double fahrenheit = (celsius * 9) / 5 + 32;

cout << "Fahrenheit degree: " << fahrenheit << endl;

cin.clear();

}

这段代码比上一段少,给出了正确答案,会转换三次,但我想不出如何显示它。

我的问题是最好的方法是什么?

最佳答案

我建议将代码拆分成更小的函数:

计算转换的那个

double celsius_to_fahrenheit(double celsius)
{
return (celsius * 9.0) / 5.0 + 32.0;
}

获取输入的那个,我选择用std::vector作为容器。你可以选择std::array<double, 3>由于数组具有固定大小,但是std::vector是一个不错的默认选择。

std::vector<double> get_input_celsius(std::size_t size)
{
std::vector<double> celsius(size);
for (std::size_t i = 0; i != celsius.size(); ++i) {
std::cout << "Celsius degree " << (i + 1) << ": ";
std::cin >> celsius[i];
}
return celsius;
}

显示结果的方法。我选择不将转换存储在新的 std::vector 中因为之后不使用它:

void display_celsius_and_fahrenheit(const std::vector<double>& celsius)
{
std::cout << std::endl << "Celsius: " << "Fahrenheit:" << std::endl;
for (auto c : celsius) { // for range since C++11
std::cout << c << " " << celsius_to_fahrenheit(c) << std::endl;
}
}

最后是 main功能:

int main()
{
std::vector<double> celsius = get_input_celsius(3);

display_celsius_and_fahrenheit(celsius);
return 0;
}

Live example

关于C++ 摄氏转华氏 3 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25627793/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com