【问题标题】:Processing a boolean in a class处理类中的布尔值
【发布时间】:2015-11-28 00:59:38
【问题描述】:

我有一个问题,我试图分配一个分数 Y 或 N,如果它是正数,然后当分数被打印出来时,它具有函数的适当符号。我不明白我是否可以将 tempchar 传递给 print 函数或如何正确打印出来。谢谢大家的帮助

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)
    {
    cout << "-";
    }
    cout << numerator << " / " << denom;
}
void fraction::inputFrac()
{    
    fraction tempchar;
    char tempchar1;

    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=1;
    }
}

【问题讨论】:

    标签: c++ function class operator-keyword


    【解决方案1】:

    您需要根据它是“Y”还是“N”来更改“正”的值。 inputFrac() 中的条件没有更新值。然后,您可以有条件地打印一条消息,如果消息为真,则使用“+”,如果为假,则使用“-”。

    *编辑:假设您的 inputFrac() 方法有效,您应该只需要以下内容:

    void fraction::printFrac()
    {
        if (!positive)
        {
            cout << "-" << numerator << " / " << denom;
        }
        else
        {
            cout << "+" << numerator << " / " << denom;
        }
    }
    

    【讨论】:

    • 你介意我问一下这样做的代码是什么吗?
    • 回答者所说的是将f(tempchar1=='Y') { positive; } 更改为f(tempchar1=='Y') { positive = 1; } - 您需要为positive 分配一个值。顺便说一句,变量tempchar 没有使用。
    • 我按照你的建议做了,但还是不行。你有什么想法为什么不呢?
    • 根据tempchar1设置positive的值,改变printFrac()动态输出值。更好的是,添加一个函数来获取正数字符串表示的值。当它为真时,你可以使用 '+' 或只是一个空字符串,根据你的要求,你可以使用 '-' 为假!
    • 我将如何更改我的代码以保持打印功能相同但使其动态和工作?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多