我如何在 C 的结构定义中引入表达式?

How might I introduce an expression in a struct definition in C?

我定义了一个结构:

struct Low {
     double high;
     double low;
     double fraction;   // = (Low.high - Low.low) / Low.high; 
     double percentage; // = Low.fraction * 100;  
} low2015, low2018, low2021, low2022;

评论暗示了我的意思。 我想在结构 Low 的定义块中引入一个表达式,这样我就不必手动进行 my_struct.fractionmy_struct.percentage

的赋值
low2021.high = 64854; 
low2021.low = 28805;
low2021.fraction = (low2021.high - low2021.low) / low2021.high;
low2021.percentage = low2021.fraction * 100;

所有四个变量,即low2015low2018low2021low2022。 我怎样才能做到这一点?

该结构足够小,可以按值返回。考虑添加函数 MakeLow().

struct Low {
     double high;
     double low;
     double fraction;
     double percentage;
};

static inline struct Low MakeLow(double high, double low) {
    return (struct Low) {
      .high = high,
      .low = low,
      .fraction = (high - low) / high,
      .percentage = (high - low) / high * 100,
    };
}

用法:

struct Low low2021 = MakeLow(64854, 28805);