为什么它 return 什么都没有?

why it does not return anything?

我正在做一个关于在某些条件下将华氏度转换为摄氏度 [C = 5/9 * (F-32)] 的编程练习:

  1. 创建一个函数 toCelsiusByReference,它通过参考获取温度,returns 一个 bool 所以:bool toCelsiusByReference(float &temperature);

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

  3. return 如果参数高于冰点 (>32 F),则为 true,return false

我做了 1 和 2,但我坚持使用 3,它对我 return 没有任何帮助。我不明白为什么?

我正在测试 60 F 的温度值,这应该 return 我是真的,因为 60 F > 32 F。

为什么我的函数 bool toCelsiusByReference(float &temperature) 没有 return 任何东西

这是代码:

#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;
}

在您的情况下,您似乎没有存储函数 (toCelsiusByReference) returns: toCelsiusByReference(temperature);.

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

的方法的期望

简而言之:

  1. 在您的 toCelsiusByReference 方法中,return 以摄氏度为单位的等效值。
  2. 在您的主程序中,添加冰点温度的逻辑。

基础知识:需要用到返回值。

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

简答:

存储函数返回的值

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