![](/img/trans.png)
[英]When I tried to run the code I was getting the 2nd output as garbage value. Can anyone tell fault in that code
[英]I tried to run this code but it keeps giving an output of else condition
字符串"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;
}
你的作业弄错了
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) {
}
这样就不可能犯你所犯的错误。
这里的问题是正确分配变量。
Temperature(int atemp, string aunit) {
temp = atemp;
unit = aunit;
}
在 C++ 中,= 运算符遵循从右到左的赋值。
你的代码在这一行是错误的。
atemp = temp;
aunit = unit;
一定是:
temp = atemp;
unit = aunit;
感谢
您的构造函数实现是错误的,您应该将输入参数分配给类成员变量,而不是其他方式:
Temperature(int atemp, string aunit)
: temp{atemp}
, unit{aunit}
{
}
应该为公共变量分配一个值,该值作为构造函数中的参数传递。 因此,在温度构造函数中:
temp = atemp and unit = aunit
最终代码:
#include <iostream>
using namespace std;
class Temperature
{
public:
int temp;
string unit;
Temperature(int atemp, string aunit)
{
temp = atemp;
unit = aunit;
}
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;
}
#include <iostream>
using namespace std;
class Temperature {
public:
int temp;
string unit;
Temperature(int atemp, string aunit) {
//atemp = temp;
//aunit = unit;
// change the assignment you will get your desired output
temp = atemp;
unit = aunit;
}
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.