c# - 数学公式设计模式

标签 c# java objective-c

例如,我需要一个计算牛顿定律 F=MA 的函数,所以我在 C# 中编写了以下代码

private double calcForce(double mass, double acceleration){
        return mass * acceleration;
}

private double calcMass(double force, double acceleration){
        return force / acceleration;
}

private double calcAcceleration(double force, double mass){
        return force / mass;
}

如果数学函数的变量数量较少(F=MA 只有 3 个),函数更复杂(我的实际任务是处理传热/流体力学函数,它很容易包含 10 个以上的变量! ) 方法的数量将等于该数学函数中的变量数量。

那么,有没有什么好的设计模式可以解决这个问题。我应该使用这样的东西吗?

private double NewtonsLaw(double? force,double? mass,double? acceleration)
{
        if(!force.HasValue)
            return mass*acceleration;
        //else if
}

还有一件事,我需要使用 Objective-C 和 Java 而不是 C# 进行编码。

最佳答案

一种方法是用您的质量/加速度/力值创建一个对象,然后(取决于设置的值)计算它们或直接返回它们

public class NewtonLaw {
    private Double mass;
    private Double acceleration;
    private Double force;

    public NewtonLaw(Double mass, Double acceleration, Double force) {
        this.mass = mass;
        this.acceleration = acceleration;
        this.force = force;
    }

    public Double calcMass() {
        if (mass != null) {
            return mass;
        } else if (acceleration == null) {
            throw new IllegalStateException("Acceleration is not set");
        } else if (acceleration == 0) {
            throw new IllegalStateException("Acceleration is zero, cannot calculate the mass");
        } else if (force == null) {
            throw new IllegalStateException("Force is not set");
        } else {
            return force / acceleration;
        }
    }

    public Double calcAcceleration() {
        if (acceleration != null) {
            return acceleration;
        } else ...
    }

    public Double calcForce() {
        if (force != null) {
            return force;
        } else ...
    }
}

不可否认,这只是一些计算的大量代码,但至少逻辑完全封装在对象中

关于c# - 数学公式设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17440612/

相关文章:

c# - MVC DropDownListFor 不从模型中选择值

c# - CodeDomProvider.CreateCompiler() 已过时

c# - 基本位图字体渲染

c# - 如何在将文件上传到 azure 之前从多部分表单数据中提取文件名和其他属性

java - 强制 read() 方法读取最少字符数

java - DES 解密/加密 java 到 python(帮助翻译)

java - 多个切换按钮会导致应用程序崩溃

ios - 在另一个 UIView 之上添加带有自己的 UIViewController 的 UIView

iphone - 动画导航栏标题

iphone - 为 iOS4.3 和 iOS5.0 构建问题