开发者

Can someone check my arithmetic for this beginner C program?

I am writing a program in C that calculates this formula:

Can someone check my arithmetic for this beginner C program?

(source: crewtonramoneshouseofmath.com)

here is the line of code (I am just using + instead of the +-):

x = ((-1 * b) + (sqrt(pow(b, 2) - 4 * a * c)))/(4 * a);

I am not getting the correct root. For example if a = 1, b=-2, and c=-2 it SHOULD be 2.73. Instead I am getting 1.37.

Been staring at the code and I don't see the mistake. Can someone point it out for m开发者_如何学编程e?


x = (...) / (4 * a)

Shouldn't this be 2 * a?


It's interesting that 1.37 (what you're getting) is about half of 2.73 (what you want) and, lo and behold, there it is in your denominator, dividing by 4a instead of 2a.

Personally, I would write that expression as:

x = (-b + sqrt (b * b - 4 * a * c)) / (2 * a);

since it more closely matches the equation you're trying to duplicate (the -1 * b is better expressed as -b) and I find calling pow to get a simple square to be unnecessary where b * b does the same job without a function call.


x1 = ((-1 * bcoeff) + (sqrt(pow(bcoeff, 2) - 4 * acoeff * ccoeff)))/(2 * acoeff);


Check yourself here: .../(4 * acoeff)


While this question has already been answered and your error pointed out. I would just like to mention that breaking the problem down into more lines would increase its readability and potentially reduce mistakes made.

float den = 2 * a;
float num1 = (-1 * b);
float num2 = pow(b ,2) - (4 * a * c);
float x = (num1 + sqrt(num2))/ den;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜