关于仅正确使用二传手和变量的问题

Question regarding using only setters and variables correctly

本文关键字:变量 问题 二传手 于仅正      更新时间:2023-10-16

我当前的编程作业有问题。我觉得我好像非常接近正确,但有些东西不对劲。我知道我必须做一些不同的事情才能使程序正常运行,因为它现在不起作用,但我不确定它是什么。

我正在为如何使用单个私有变量来产生两种温度而苦苦挣扎。

这是作业:

设置温度类。 该类应具有以华氏度设置温度的函数和以摄氏度设置温度的功能。 在专用部分中仅保留一个数据成员以存储温度。 创建一个用于获取华氏度的函数和一个用于获取以摄氏度为单位的温度的函数。 使用驱动程序彻底测试每个函数。

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

只需使用一个特定的单位在内部存储温度,最好是开尔文1IMO(因为它是标准的 SI 物理单位(。

在将温度设置或设置为华氏度或摄氏度时进行必要的计算。

也不要使用整数除法来表示分数:
(5/9)结果是整数除0,则应(5.0/9.0)获得有效的double值。
9/5相同,因为整数除法将产生1


代码的其他问题:

  1. 在您的函数double converter(double temperature)中,您尝试使用f,这不在范围内
  2. 在同一函数中,您有一个名为temperature的参数,该参数以相同的名称隐藏您的成员变量

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

您的问题是因为您正在尝试将温度值与初始变量名称进行比较,以确定它是华氏度还是摄氏度。

if (temperature = f)
...
else if (temperature = c))

您应该选择一种温度类型而不是另一种温度类型,以始终将值存储为并在需要时转换为另一种温度类型。 在本例中,使用摄氏

void set_celsius(double c)
{
temperature = c;
}
void set_fahrenheit(double f)
{
temperature = (5.0/9.0)(f - 32);
}

您的华氏吸物也可以这样做。您的转换器方法确实不需要(并且不称为 atm(。

编辑

您还应该使用浮点数学,因为整数数学将被截断为 0,因为您追求的值是十进制 0.5555...

将该值存储为所需温度之一将节省需要该温度类型的计算。 在此代码中,它不会有什么不同,但是在扩展软件时,消除过多的处理非常重要。