比较if语句中结构内部的值

时间:2013-01-17 23:45:17

标签: c++

我正在用C ++编写一个分数简化器。我试图比较一个结构中的两个值,看看哪个更大,以下工作都没有:

void simplify(struct Fraction* fraction) {
    if (fraction->numerator) > (fraction->denominator)
    {
        cout << "test";
    }
}

void simplify(struct Fraction* fraction) {
    if (fraction.numerator) > (fraction.denominator)
    {
        cout << "test";
    }
}

STRUCT:

struct Fraction {
    int numerator;
    int denominator;
};

错误:

w2.cpp: In function void simplify(Fraction*):
w2.cpp:40:15: error: request for member numerator in fraction, which is of non-class type Fraction*
w2.cpp:40:26: error: expected primary-expression before > token
w2.cpp:40:38: error: request for member denominator in fraction, which is of non-class type Fraction*
w2.cpp:41:2: error: expected ; before { token

我如何比较结构内部的值?

2 个答案:

答案 0 :(得分:4)

你有指针,所以你需要取消引用它们。你也有支架问题:

void simplify(struct Fraction* fraction) {
    if (fraction->numerator > fraction->denominator)
    {
        cout << "test";
    }
}

您可以通过传递引用来避免所有这些指针去引用问题。此外,放弃不必要的struct s

void simplify(const Fraction& fraction) {
    if (fraction.numerator > fraction.denominator) {
        cout << "test";
    }
}

答案 1 :(得分:2)

你只是错过了一对括号:

void simplify(struct Fraction* fraction) {
    if ( (fraction->numerator) > (fraction->denominator) )
    {
        cout << "test";
    }
}