为什么它不返回任何东西?

时间:2020-11-06 08:21:29

标签: c++ function return boolean

我正在进行一些编程练习,将华氏温度转换为摄氏温度[C = 5/9 *(F-32)]:

  1. 创建一个toCelsiusByReference函数,该函数通过引用获取温度,然后返回一个布尔值:bool toCelsiusByReference(float&temperature);

  2. 将参数从华氏温度更改为等效摄氏温度

  3. 如果参数高于冻结(> 32 F),则返回true;返回false

我做了1和2,但我坚持使用3,这对我没有任何回报。我不明白为什么?

我正在测试60 F作为温度,因为60 F> 32 F,应该返回true。

为什么我的函数bool toCelsiusByReference(float &temperature)不能返回任何内容

这是代码:

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

bool toCelsiusByReference(float &temperature);

int main()
{
    float temperature = 60;
    toCelsiusByReference(temperature);
    return 0;
}

bool toCelsiusByReference(float &temperature)
{
    float celsius;
    bool status;

    // convert celsius to Fahrenheit
    cout.setf(ios::fixed, ios::floatfield);
    celsius = 5.00 / 9.00 * (temperature - 32);
    // cout << "Degrees C : " << setprecision(2) << celsius << endl;

    // check if temperature (fahrenheit) is freezing (<32) or not
    if (temperature > 32)
    {
        status = true;
    }
    else
    {
        status = false;
    }

    return status;
}

3 个答案:

答案 0 :(得分:3)

在您的情况下,您似乎没有存储函数(toCelsiusByReference)返回的内容:toCelsiusByReference(temperature);

现在,从编码角度来看,我建议进行一些更改。尝试使您的方法尽可能简单。在您的情况下,您正在对转换机制进行温度检查,至少在我看来,这种检查不应存在。 这也使该方法的名称有点误导,因为truefalse并不是人们对toCelsiusByReference方法的期望。

简而言之:

  1. 在您的toCelsiusByReference方法中,返回以摄氏度为单位的等效值。
  2. 在您的主菜单中,添加凝固点温度的逻辑。

答案 1 :(得分:2)

基本知识:您需要以某种方式使用返回值。

...
if (toCelsiusByReference(temperature))
{
  cout << "above 32°F\n";
}
else
{
 cout << "below 32°F\n";
}
cout << "Converted temperature: " << temperature << " °C\n";
...

答案 2 :(得分:1)

简短答案:

存储从函数返回的值

int main
{
  ...
  bool b = toCelsiusByReference(...)
}