更新布尔值时,类中的打印函数不更新

Print function in a class not updating when boolean is updated

本文关键字:更新 打印 函数 布尔值      更新时间:2023-10-16

所以我有一个程序,用于我正在编写的一个类,除了print函数之外,其他都完成了。输入函数是正确的,布尔值将在输入函数中更新,但当我尝试转移到打印函数时,它总是打印(-),如果用户输入"Y",则假设它绕过(-)并只打印分数。如果有人想让它发挥作用,我觉得我什么都试过了。

编辑:当我只打印出主要的两个分数f1和f2时,打印函数就可以工作了,但我相信,当把正数传给打印函数时,问题就来了。

class fraction
{
    private:
        int numerator;
        int denom;
        bool positive;
    public:
        void inputFrac();
        void printFrac();
        fraction fracMult(fraction& b);
        fraction fracDiv(fraction& b);
        fraction fracAdd(fraction& b);
        fraction fracSub(fraction& b);
};
 void fraction::printFrac()
{
 if (positive=true)
    {
        cout << "-" << numerator << " / " << denom;
    }
    else
    {
        cout << "+" << numerator << " / " << denom;
    }
}
void fraction::inputFrac()
{    
    char tempchar1;
    fraction tempchar;
    cout<<"Please input the numerator ";
    cin>>numerator;
    cout<< "Please input the denominator ";
    cin>>denom;
    cout<<"Is the fraction positive? (Y or N) ";
    cin>>tempchar1;
    if((tempchar1=='Y'))
    {
        positive=true;
    }
    else
    {
        positive=false;
    }
}

您在if语句中进行赋值。更改:

 if (positive=true)

至:

 if (positive==true)

在printFrac函数中,您有if (positive=true)。这是不正确的,因为你正在做什么。您应该使用if (positive) {/*stuff*/}