![](/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.