-4

我正在用 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 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

如何比较结构内的值?

4

2 回答 2

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";
    }
}
于 2013-01-17T23:47:18.057 回答
2

您只是缺少一对括号:

void simplify(struct Fraction* fraction) {
    if ( (fraction->numerator) > (fraction->denominator) )
    {
        cout << "test";
    }
}
于 2013-01-17T23:47:00.750 回答