创建一个将Centigrade转换为Wahrenheit的课程,反之亦然

Creating a Class to convert Centigrade to Fahrenheit and vice versa

本文关键字:Wahrenheit 反之亦然 转换 Centigrade 一个 创建      更新时间:2023-10-16

我最近在我的高中课程中开始在C 上编程。我目前正在学习课程,并且我遇到了一些麻烦,可以创建一门课程,该课程将从Centigrade转换为华氏和华氏度,再到Centigrade。我觉得我完全做错了。任何帮助都会很棒。该程序运行良好,但不转换,我该如何抓住" dcent"answers" dfahr"并在转换类中使用它?

#include <iostream>
using namespace std;
int main() {
    int nUserInput;
    double dCent, dFahr;
    cout << "Do you want to convert from Centigrade to Fahrenheit [1] or from Fahrenheit to Centigrade [2]" <<endl;
    cin >> nUserInput;
    if (nUserInput == 1) {
        cout << "Enter the Centigrade" <<endl;
        cin >> dCent;
    } else if (nUserInput == 2) {
        cout << "Enter the Fahrenheit" <<endl;
        cin >> dFahr;
    }
    Convert tempConverter;
    tempConverter.
}

class Convert {
public:
    void centToFahr() {
        //dCent = dCent * 9 / 5 + 32;
    }
    void fahrToCent() {
        //dCent = (dFahr - 32) * 5 / 9;
    }
};

尝试以下:

    class Convert {
public:
    double centToFahr(double dCent) {
        return dCent * 9 / 5 + 32;
    }
    double fahrToCent(double dFahr) {
        return (dFahr - 32) * 5 / 9;
    }
};
int main() {
    int nUserInput;
    double dCent, dFahr;
    Convert tempConverter;
    cout << "Do you want to convert from Centigrade to Fahrenheit [1] or from Fahrenheit to Centigrade [2]" << endl;
    cin >> nUserInput;
    if (nUserInput == 1) {
        cout << "Enter the Centigrade" << endl;
        cin >> dCent;
        cout << "dFahr = " << tempConverter.centToFahr(dCent);
    }
    else if (nUserInput == 2) {
        cout << "Enter the Fahrenheit" << endl;
        cin >> dFahr;
        cout << "dCent = " << tempConverter.fahrToCent(dFahr);
    }
}

我遇到了一些麻烦,可以创建一堂课,该课程将从摄氏(Centigrade)转变为华氏和华氏(Wahrenheit),再到Centigrade。

选项1

  1. 您可以将温度存储为成员变量。
  2. 更改函数以返回值,而不是使用void返回类型。

class Convert
{
   public:
      Convert(double val) : val_(val) {}
      double centToFahr() {
         return (val_* 9 / 5 + 32);
      }
      double fahrToCent() {
         return (val_ - 32) * 5 / 9
      }
   private:
      double val_;
};

选项2

选项1 中的解决方案遇到了Convert不知道其存储的值是Centigrade还是在华氏度中的问题。如果您致电centToFahr,则将该值视为摄氏。如果您致电fahrToCent,则该值将在华氏度。

您最好完全没有成员变量,并期望温度值作为参数。

class Convert
{
   public:
      // OK to assume val to be in Centigrade
      double centToFahr(double val) {
         return (val * 9 / 5 + 32);
      }
      // OK to assume val to be in Fahrenheit
      double fahrToCent(double val) {
         return (val - 32) * 5 / 9
      }
};