C#中平方根计算方法及公式代码结果不符问题求助
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

