【问题标题】:Print function in a class not updating when boolean is updated更新布尔值时类中的打印函数未更新
【发布时间】:2015-11-30 17:31:14
【问题描述】:

所以我有一个我正在编写的类的程序,除了打印功能之外,它都已完成。输入函数是正确的,布尔值将在输入函数中更新,但是当我尝试转移到打印函数时,它总是打印(-),如果用户输入“Y”,那么假设绕过(-)和只需打印出分数。如果有人无论如何要让它工作,我觉得我已经尝试了一切。

编辑:当我只打印出 main 中的两个分数 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;
    }
}

【问题讨论】:

    标签: c++ function class printing boolean


    【解决方案1】:

    您在 if 语句中进行分配。 变化:

     if (positive=true)
    

    到:

     if (positive==true)
    

    【讨论】:

    • 甚至:if (positive)
    • 这是一个很好的例子,你最好习惯于以if ([value] == variable) 的形式写ifs、whiles 和其他条件语句。因为即使你犯了一个错误,写了=而不是==,你也会得到一个编译错误。诚然,如果您要比较 2 个非常量变量,这将无济于事,但至少有助于消除一些此类错误。
    • 我添加了这个并且分数打印出来,无论第一个符号是什么,所以即使我在询问它是否为正时我为两个分数都输入了 Y,它也会继续用 (-) 打印出来编辑:打印功能有效,我只是用 f1 和 f2 尝试过,它用正确的符号打印出来,但由于某种原因,当它们通过函数时我去打印它们不起作用
    • 一方面,if 语句实际上是倒退的......它正在做:if (positive) cout
    【解决方案2】:

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

    【讨论】:

    • 我添加了这个并且分数打印出来,无论第一个符号是什么,所以即使我在询问它是否为正时我为两个分数都输入 Y,它也会继续打印出 (-)
    猜你喜欢
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多