【发布时间】:2022-06-22 05:34:19
【问题描述】:
字符串"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;
}
【问题讨论】:
-
在构造函数中应该是
temp = atemp;而不是其他方式。 -
并使用初始化列表
-
您没有保存参数。此外,您正在进行双重转换 - F 应该产生 C ,反之亦然。 F 不应该产生 F。
-
我尝试了@kotatsuyaki 评论的更改,这就是问题所在。谢谢你:)
-
是的,我错过了那个。感谢您指出这一点! @杯子
标签: c++