c-有关仅正确使用设置器和变量的问题

我目前的编程工作遇到问题.我觉得我似乎已经很接近正确了,但是有些问题了.我知道我必须做一些不同的事情才能使程序正确运行,因为它目前无法正常工作,但是我不确定它是什么.

我特别在努力使用单个私有变量来同时产生两种温度.

这是作业:

Make a Temperature class. The class should have a function for setting the temperature in Fahrenheit and function for setting a temperature in Celsius. Keep only one data member in the private section for storing the temperature. Create a function for obtaining the in Fahrenheit and a function for obtaining the temperature in Celsius. Test each function thoroughly with a driver.

F = (9/5)C + 32, C = (5/9)(F – 32)

当前代码:

#include<iostream>
using namespace std;

class Temperature
{
private:
    double temperature;

public:
    void set_fahrenheit(double f)
    {
        temperature = f;
    }

    void set_celsius(double c)
    {
        temperature = c;
    }

    double get_fahrenheit()
    {
        return temperature;
    }

    double get_celsius()
    {
        return temperature;
    }

    double converter(double temperature)
    {
        if (temperature = f)
        {
            return (9/5)*temperature + 32;
        }
        else if (temperature = c))
        {
            return (5/9)*(temperature - 32;
        }
    }    
};

int main()
{
    Temperature Temp1;
    double temperaturetemp;
    string response;

    cout << "Would you like to convert a Celsius temperature to Fahrenheit or convert a Fahrenheit temperature to Celsius? (Enter C2F or F2C respectively)" << endl;
    cin >> response;

    cout << "Please enter the temperature you would like to convert in degrees" << endl;
    cin >> temperaturetemp;

    if (response == "C2F"){Temp1.set_fahrenheit(temperaturetemp);}
    else if (response == "F2C"){Temp1.set_celsius(temperaturetemp);}

    cout << Temp1.converter(temperaturetemp);
 }

解决方法:

只需使用一个特定的单位内部存储温度,最好是Kelvin1 IMO(因为它是标准的SI物理单位).

将温度设置为华氏度或摄氏度时,请进行必要的计算.

也不要使用整数除法来表示分数:
(5/9)将结果为0整数除,它应该是(5.0 / 9.0)才能获得有效的double值.
与9/5相同,因为整数除法将得出1.

您的代码的其他问题:

>在函数双转换器(双温度)中,您尝试使用f,f不在此范围内
>在同一函数中,您有一个名为temperature的参数,该参数以相同的名称遮盖了成员变量

1)0K = -459,67F / 0K = -273.15°C

上一篇:java – 如何在Spring Framework中运行setter?


下一篇:c#-SingleOrNewIdentified(o => o.prop,value),新建时设置o.prop