gpt4 book ai didi

c++ - 两次请求用户输入

转载 作者:行者123 更新时间:2023-11-28 05:26:00 26 4
gpt4 key购买 nike

更新:已回答!谢谢@Ken Y-N 我非常感谢你的帮助!!

免责声明:我是第一学期的 c++ 学生,我不知道自己在做什么,而且我的教科书非常困惑。此外,代码的风格对于给定的分配是强制性的。请继续了解这些知识!

OP:我有一个代码可以将华氏温度转换为摄氏温度并显示摄氏温度。但是,它两次要求输入华氏温度。我已经尝试在我能想到的任何地方(以及其他线程中推荐的地方)更改代码,但它要么不能解决问题,要么会导致其他错误并且不会正确构建。预先感谢您的帮助,这是我最新功能构建的代码:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

//declare function prototypes
double getFahrenheit();
double calcCelsius();

int main()
{
double fahrenheit = 0.0;
double celsius = 0.0;

//call getFahrenheit function
fahrenheit = getFahrenheit();

//call calcCelsius function
celsius = calcCelsius();

//display temperature in degrees celsius
cout << "The temperature is: " << celsius << endl;
return 0;
} //end of main function

double getFahrenheit()
{
double fahrenheitTemp = 0.0;
cout << "Enter temperature in Fahrenheit: " << endl;
cin >> fahrenheitTemp;
return fahrenheitTemp;
}

double calcCelsius()
{
double fahrenheit = getFahrenheit();
double celsiusTemp = 5.0 / 9.0 * (fahrenheit - 32.0);
return celsiusTemp;
}

我认为错误与:

//call getFahrenheit function
fahrenheit = getFahrenheit();

还有“双华氏 = getFahrenheit();”此函数中的行:

double calcCelsius()
{
double fahrenheit = getFahrenheit();
double celsiusTemp = 5.0 / 9.0 * (fahrenheit - 32.0);
return celsiusTemp;
}

不过,我还是想不出还有什么其他方法可以编写此代码,并且在保持我的讲师所要求的结构的同时仍然具有功能构建。这一章真的很挣扎!

最佳答案

正如您所确定的,问题是您调用了两次 getFahrenheit()。 (实际上问题是“我不知道我在做什么”,但让我们掩盖这一点。)一个解决方案是使 fahrenheit 成为 calcCelsius() 的参数,所以我们得到:

double calcCelsius(double fahrenheit);

//...

celsius = calcCelsius(fahrenheit);

//...

double calcCelsius(double fahrenheit)
{

//...

这应该足以让您接近答案。

关于c++ - 两次请求用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40541482/

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