简体   繁体   中英

How to take square root in c#

I have a formula that I want to write in C#. Please find a mistake if any... 公式图片 .
I'm writing in my code same like this:

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

Unfortunately, the results from this are not the same as the formula. How can I fix it?

You're missing a set of parentheses around the denominator. Without them, everything inside the sqrt is getting computed left to right.

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

Also a set around the last factor. Thanks Joel.

It needs either more parentheses or to break up the calculation over multiple statements (or both). Otherwise, the square root expression only divides by H4 and then multiples that result by Cy and n .

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

Even better if you know enough about why the formula is what it is to give the numerator and denominator values meaningful names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM