You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中平方根计算方法及公式代码结果不符问题求助

Fixing Your C# Formula & Understanding Square Root Calculations

Hey there! Let's work through your problem step by step to get that formula matching your expected results, and clear up how square roots work in C#.

1. Why Your Formula Isn't Matching the Original

The most likely culprit here is missing parentheses causing incorrect operator precedence. In C#, multiplication (*) and division (/) have the same priority, so they’re evaluated left-to-right.

Looking at your current code:

Xopt = 293.94 * Math.Sqrt(HDD * Cfuel * PWF * K / H4 * Cy * n) - K * Rwt;

The expression inside Math.Sqrt gets calculated as:
((((HDD * Cfuel) * PWF) * K) / H4) * Cy) * n

But it’s almost certain your original formula has the square root covering a fraction where all denominator terms are grouped together (like (HDD*Cfuel*PWF*K) / (H4*Cy*n)). To enforce this grouping, wrap the denominator in parentheses:

Corrected Formula

Xopt = 293.94 * Math.Sqrt( (HDD * Cfuel * PWF * K) / (H4 * Cy * n) ) - K * Rwt;

If your original formula has a different structure for the square root term, adjust the parentheses to match exactly what the formula specifies. A quick debug trick: isolate the square root input into a separate variable and print it, then compare it to a manual calculation of the original formula:

double sqrtInput = (HDD * Cfuel * PWF * K) / (H4 * Cy * n);
Console.WriteLine($"Square root input: {sqrtInput}"); // Compare this to manual calculation
Xopt = 293.94 * Math.Sqrt(sqrtInput) - K * Rwt;

2. Calculating Square Roots in C#

C# has straightforward options for square root calculations, depending on your needs:

Basic Non-Negative Square Roots

The standard method is Math.Sqrt(double value) from the System namespace. It returns the square root of a non-negative double value. If you pass a negative number, it throws an ArgumentOutOfRangeException, so validate inputs if there’s a chance they could be negative:

double value = 16;
double squareRoot = Math.Sqrt(value); // Returns 4.0

// Handle potential negative values
double riskyValue = ...;
double safeSqrt;
if (riskyValue >= 0)
{
    safeSqrt = Math.Sqrt(riskyValue);
}
else
{
    // Add custom error handling here (e.g., return 0, log a warning)
    safeSqrt = 0;
    Console.WriteLine("Cannot calculate square root of a negative number.");
}

Complex Number Square Roots

If you need to calculate the square root of a negative number (resulting in a complex number), use Complex.Sqrt from the System.Numerics namespace (add a reference to the System.Numerics assembly first):

using System.Numerics;

Complex negativeValue = new Complex(-16, 0);
Complex complexSqrt = Complex.Sqrt(negativeValue); // Returns (0, 4)

内容的提问来源于stack exchange,提问作者Malik Asad Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:49:38