字符串"Fahrenheit"应该给出第一个if语句的输出,但是它会释放else语句的输出。
#include <iostream>
using namespace std;
class Temperature {
public:
int temp;
string unit;
Temperature(int atemp, string aunit) {
atemp = temp;
aunit = unit;
}
void to_fahrenheit() {
if (unit == "Fahrenheit") {
cout << ((temp*1.8) + 32) << " Fahrenheit";
} else if (unit == "Celsius") {
cout << ((temp-32)*5/9) << " Celsius";
} else {
cout << "Converts only Fahrenheit to Celsius or vice versa.";
}
}
};
int main() {
Temperature temp1 (10,"Fahrenheit");
temp1.to_fahrenheit();
return 0;
}发布于 2022-06-06 06:55:16
你的作业错了
Temperature(int atemp, string aunit) {
atemp = temp;
aunit = unit;
}应该是
Temperature(int atemp, string aunit) {
temp = atemp;
unit = aunit;
}这是一个逻辑错误,而不是语法错误。
编写此代码的最佳方法是使用初始化程序列表。
Temperature(int atemp, string aunit) : temp(atemp), unit(aunit) {
}这样就不可能犯你所犯的错误了。
发布于 2022-06-06 06:56:02
这里的问题是如何正确地分配变量。
Temperature(int atemp, string aunit) {
temp = atemp;
unit = aunit;
}在C++中,=运算符遵循从右到左的分配。
发布于 2022-06-06 06:56:51
您的代码在这一行是错误的。
atemp = temp;
aunit = unit;必须:
temp = atemp;
unit = aunit;谢谢
https://stackoverflow.com/questions/72514004
复制相似问题