Skip to main content
 首页 » 编程设计

c#之转换为 c# 的 Excel 公式未给出相同的结果

2024年02月13日14yxwkf

我在excel中有一个公式

SUM((((25+273))/((40+273))*((688.00*1.001)+101.325))-101.325)-8.46 

这个公式给我的答案是 642.36

我将这个公式翻译成下面的 C# 函数

public decimal CalculateBaselinePressure(decimal baselineTemperature,  
                                         decimal knownTemperature,  
                                         decimal knownPressure) 
{ 
    return (baselineTemperature + 273) / (knownTemperature + 273) *  
           (((knownPressure * 1.001m) + 101.325m) - 101.325m) -8.46m; 
} 

这给了我 647.22378274760383386581469649M 的答案

知道为什么公式没有给出相同的答案。

请您参考如下方法:

您的括号有所不同。这是 Excel 公式的简化但等效版本:

(a+273) / (b+273) * (c*1.001 + 101.325) - 101.325 - 8.46 

这就是您的 C# 表达式分解成的内容

(a+273) / (b+273) * ((c*1.001 + 101.325) - 101.325) - 8.46; 

您需要在乘法后删除一组括号。此外,您可能应该使用 double 而不是 decimal:

public static double CalculateBaselinePressure( 
    double baselineTemperature, 
    double knownTemperature, 
    double knownPressure) 
{ 
    return (baselineTemperature + 273) / (knownTemperature + 273) * 
        ((knownPressure * 1.001d) + 101.325d) - 101.325d - 8.46d; 
}