Josie0625
Josie0625
采纳率54.5%
2019-07-15 14:19

c++报错x was not declared in this scope 其中x是对象的名 求助一下为什么会报错呢

已采纳

新手求轻喷......

#include

using namespace std;

class People
{
public:
People(int i,float j);
~People(){}
float calculateBMI(int myWeight,float myHeight);
void getAnswer();
private:
int myWeight;
float myHeight,myBMI;
};
People::People(int i,float j)
{
myWeight=i;
myHeight=j;
}
float People::calculateBMI(int myWeight,float myHeight)
{
float myBMI;
myBMI=myWeight/(myHeight*myHeight);
return myBMI;
}
void People::getAnswer()
{
if(myBMI>=18.5&&myBMI<=23.9)
cout<<"No!"<<endl;
else
cout<<"Yes!"<<endl;
}

int main()
{
int myWeight;
float myHeight;
while(cin>>myWeight>>myHeight)
People x(int myWeight,float myHeight);
x.calculateBMI(myWeight,myHeight);
x.getAnswer();
return 0;
}


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • adgentleman adgentleman 2年前

    1.因为你的x是在while循环定义的,所以当循环条件不成立的时候相当于x没有定义
    2.然后创建x的时候还有点问题,
    People x(int myWeight,float myHeight);
    参数只需要传变量名,改成
    People x(myWeight,myHeight);

    以下是我改的main函数,编译运行没问题
    int main()
    {
    int myWeight=1;
    float myHeight=1.5;
    // while(cin>>myWeight>>myHeight)
    People x(myWeight,myHeight);
    x.calculateBMI(myWeight,myHeight);
    x.getAnswer();
    return 0;
    }
    希望帮到你

    点赞 1 评论 复制链接分享
  • qq_45407296 qq_45407296 2年前

    #include
    using namespace std;
    class People
    {
    private:
    int myWeight;
    float myHeight;
    float myBMI;
    public:
    People(int w,float h)
    {
    myWeight=w;
    myHeight=h;
    }
    void calculateBMI()
    {
    myBMI=myWeight/(myHeight*myHeight);
    }
    void getAnswer()
    {
    calculateBMI();
    if(myBMI>23.9)
    {
    cout<<"Yes!"< }
    else
    {
    cout }
    }
    };
    int main()
    {
    int w;
    float h;
    while(cin>>w>>h)
    {
    People people(w,h);
    people.getAnswer();
    }
    return 0;
    }
    我觉得这样子写舒服一点

    点赞 评论 复制链接分享
  • qtchen_1988 qtchen_1988 2年前
    while(cin>>myWeight>>myHeight)
    People x(int myWeight,float myHeight);
    x.calculateBMI(myWeight,myHeight);
    x.getAnswer();
    
    -->
    while(cin>>myWeight>>myHeight)
    {
        People x(myWeight,myHeight);
        x.calculateBMI(myWeight,myHeight);
        x.getAnswer();
    }
    
    点赞 评论 复制链接分享

相关推荐