[英]Why does this test always return false?
請忽略此代碼的上下文。 想法是名為shop()
的函數將采用兩個參數( money_in_pocket
, age
),並確定這些值是否會使它們進入Rolex商店。 但是,即使參數滿足shop()
if語句的要求,程序也會繼續輸出“ Leave!”-表示離開商店。
您可能已經注意到,我是該語言的新手,所以對您的幫助將不勝感激。
我試着使參數遠大於if
語句要求的參數。 輸出為“ leave!”,因此我嘗試了不符合要求的參數,並顯示了相同的輸出...
#include <iostream>
using namespace std;
class rolex{
public:
bool shop(int x, int y){
if((x >= 5000 && y>= 18)||(x>=5000 && y<18)){
bool enterence = true;
}else{
bool enterence = false;
};
return enterence;
}
private:
bool enterence;
};
int main()
{
rolex objj;
if( objj.shop(5000, 18) == true){
cout<<"you may enter"<<endl;
}else{
cout<<"LEAVE"<<endl;
}
return 0;
}
在if語句中
if((x >= 5000 && y>= 18)||(x>=5000 && y<18)){
bool enterence = true;
}else{
bool enterence = false;
};
您聲明了兩個退出if語句后將不活動的局部變量。
因此,數據成員rolex::enterence
未初始化,並且具有不確定的值。
像這樣更改if語句
if((x >= 5000 && y>= 18)||(x>=5000 && y<18)){
enterence = true;
}else{
enterence = false;
};
考慮到if語句中的條件等於
if( x >= 5000 ){
您可以只寫而不是if語句
enterence = x >= 5000;
要么
rolex::enterence = x >= 5000;
這是對程序的簡單編輯,可以按預期工作:
#include <iostream>
using namespace std;
class rolex {
private:
bool entrance;
public:
bool shop(int x, int y) {
if(x >= 5000 && y>= 18) {
entrance = true;
} else {
entrance = false;
}
return entrance;
}
};
int main() {
rolex obj;
if(obj.shop(5000, 18) == true) {
cout << "you may enter" << endl;
} else {
cout << "LEAVE" << endl;
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.