如何在未输入但根据先前变量的值设置的结构变量中创建变量

How to make a variable in a struct variable that is not inputted but set based on previous variables' values

我正在制作一个输入分数并将它们排序的程序。我使用 struct 来定义分数类型。我想我正在制作一个类型来初始化 2 个变量(分数的分子和分母)并在这段代码中将名为 value 的 double 类型变量初始化为 a / b:

struct fraction {
    int a; // numerator
    int b; // denominator
    double value = a / b; // floating point value of fraction
    bool operator > (const fraction &a) {
        fraction ans;
        return ans.value > a.value;
    }
    bool operator < (const fraction &a) {
        fraction ans;
        return ans.value < a.value;
    }

};



int main() {
//---------logging-------
    fraction ratio = {1,2};
    cout << ratio.value;
//-----------------------
    // outputs 0
    // other things down here that is not included
}

但显然,情况并非如此,因为我还需要初始化值。我想通了为什么,但问题是,如何在创建分数时不初始化变量来创建变量?谢谢!

我认为有两种解决方案,要么将 a 和 b 初始化为 0,要么每次需要时都计算 a/b。

...或者您可以编写一个异常,例如:

int a;
int b;
double val;

try() { val = a/b; }
catch(...){ val = 0; }

我不认为那很好,因为它总是很容易被抓住。

How can I make the variable without initializing it at the creation of the fraction?

可以只写一个成员函数 double value() 来计算和返回分数的浮点值,但首先在发布的代码中有一些问题需要解决(实际上可能会解决 OP 的问题问题)。

  • 显示的唯一 in-class 成员变量初始化不正确。

    double value = a / b; // floating point value of fraction
    

    同时 ab 类型的 int 变量,a / b 是一个 整数 除法,产生 int 仅在分配给 double 变量后的结果。在 OP 的示例中,int(1)/int(2) == int(0).

    为了产生期望值,我们需要明确地将至少一项转换为 double:

    double value = static_cast<double>(a) / b;
    
  • 两个比较运算符都是错误的。

    bool operator > (const fraction &a) {
          fraction ans;                // This is a LOCAL, UNINITIALIZED varible.
          return ans.value > a.value;  // The result is meaningless.
    }
    

以下代码片段显示了一种可能的实现方式,其中计算 value 而不是存储(这不一定是个好主意)。

#include <iostream>
#include <numeric>

class fraction
{
    int numerator_{}; 
    int denominator_{1}; 

public:
    fraction() = default;
    fraction(int num, int den)
        : numerator_{num}, denominator_{den}
    {
        if (auto divisor = std::gcd(num, den); divisor != 1)
        {
            numerator_ /= divisor;
            denominator_ /= divisor;
        }
    }

    bool operator > (fraction const& a) const noexcept {
        return value() > a.value();
    }

    bool operator < (fraction const& a) const noexcept {
        return value() < a.value();
    }

    auto numerator() const noexcept {
        return numerator_;
    }

    auto denominator() const noexcept {
        return denominator_;
    }

    double value() const noexcept {
        return static_cast<double>(numerator_) / denominator_;
    }
};