为什么这个测试总是返回假

Why does this test always return false?

本文关键字:返回 测试 为什么      更新时间:2023-10-16

请忽略此代码的上下文。这个想法是 名为 shop() 的函数将采用两个参数 (money_in_pocketage(并确定这些值是否会 让他们进入劳力士专卖店。然而,即使当 参数满足 if 语句的要求 shop(),程序继续输出"离开!- 意思是离开商店。

您可能已经注意到,我是该语言的新手,所以任何 帮助将不胜感激。

我尝试使参数远大于if 声明要求他们成为。这输出了"离开!",所以我尝试了不符合要求的参数,并且 显示相同的输出...

#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;
}