关于仅正确使用二传手和变量的问题
Question regarding using only setters and variables correctly
我当前的编程作业有问题。我觉得我好像非常接近正确,但有些东西不对劲。我知道我必须做一些不同的事情才能使程序正常运行,因为它现在不起作用,但我不确定它是什么。
我正在为如何使用单个私有变量来产生两种温度而苦苦挣扎。
这是作业:
设置温度类。 该类应具有以华氏度设置温度的函数和以摄氏度设置温度的功能。 在专用部分中仅保留一个数据成员以存储温度。 创建一个用于获取华氏度的函数和一个用于获取以摄氏度为单位的温度的函数。 使用驱动程序彻底测试每个函数。
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
。
代码的其他问题:
- 在您的函数
double converter(double temperature)
中,您尝试使用f
,这不在范围内 - 在同一函数中,您有一个名为
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...
将该值存储为所需温度之一将节省需要该温度类型的计算。 在此代码中,它不会有什么不同,但是在扩展软件时,消除过多的处理非常重要。
- 为"adjacent"变量赋值时出现问题
- C++理解计算字符变量的问题
- 在通知提升间处理条件变量时未按住锁会导致问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 将十六进制值设置为用于填充的字符变量时出现问题
- 初学者问题:如何访问此变量?
- 关于仅正确使用二传手和变量的问题
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- C++ 多线程中的锁和条件变量问题
- C++grpc的一些变量问题
- 我如何加载多个脚本而没有变量问题
- 未初始化的变量问题C++
- C++和引脚工具 - IF语句非常奇怪的双变量问题
- 如何通过引用捕获异常来解决局部变量问题
- sscanf写入变量问题
- 影子变量问题Qt
- C++ 中的局部变量问题
- 跨平台条件变量问题
- Makefile变量问题,make想要创建"*.o"而不是foo.o bar.o等
- c++变量问题