变量名称中物理单位的样式?

Cam*_*une 7 c c++ physics coding-style units-of-measurement

Are there any Hungarian-in-spirit style guides for appending (SI or Imperial) units to variable names for physics-intensive C/C++? I'd expected that this wheel had already been invented, but online I found only simple examples like duration_sec and length_ft. (No boost, please.) (Roughly related: naming of physical quantities in python .)

Typeset prose has a good style guide, but its superscripts, slashes and italics fail in programming languages.

I'd even be happy with arguments resolving particular issues that arise with compound units like spectral radiance, moment, torque, or energy:

  • plural or not (lbs, lb)
  • capital or not (Lb, lb)
  • reciprocals (PerSec, pSec, SecInv)
  • superscripts like cubed or inverse squared

Kev*_*vin 6

最终,重要的是选择一种风格并坚持下去。

如果我要实现这个,我可能会从 SI 缩写开始:

int distance_m; // meters
Run Code Online (Sandbox Code Playgroud)

对于指数,将指数附加到单位:

int area_m2; // square meters
Run Code Online (Sandbox Code Playgroud)

对于产品,用下划线分隔:

int torque_N_m; // Newton-meters
Run Code Online (Sandbox Code Playgroud)

(此处资本的使用N可能是好主意,也可能不是好主意;保持一致)

对于商,写per

int velocity_m_per_s; // meters per second
Run Code Online (Sandbox Code Playgroud)

每个变量应该只需要一个per。假设它的优先级低于乘法。

当然,以上只是一个建议;您应该修改它以满足您的需要。只要确保整个开发团队都同意这些规则即可。

  • @WeatherVane (e/t)/a = (e/t) * (1/a) = e/at,所以使用这个答案的约定将是“joule_per_m2_s”或“watt_per_m2”,这是非常明智的。任何其他嵌套分数都可以用同样的方式展平,尽管可能并不总是有如此好的结果。但是(某些类型的)工程师通常会在计算中处理大量单位,这是可以管理的。 (2认同)