给定a=1、b=5和c=6的值,x的值应该是-2和-3,但是下面的程序给出的x的值是6和-11,这是不正确的。如果有人能找出程序出了什么问题,我将不胜感激。
#include<iostream.h>
#include<conio.h>
int main()
{
char reply;
int a,b,c,q,z;
do
{
cout<<"Enter the value of a: ";
cin>>a;
cout<<"\nEnter the value of b: ";
cin>>b;
cout<<"\nEnter the value of c: ";
cin>>c;
q=(-b-(b*b-4*a*c)sqrt(b))/2/a;
z=(-b+(b*b-4*a*c)sqrt(b))/2/a;
cout<<"\nThe values of x are "<<q<<" and "<<z;
cout<<"\nDo you want to find another values of x(y/n)?";
cin>>reply;
}
while(reply=='y');
getch();
return 0;
}发布于 2011-12-18 23:36:04
变化
q=(-b-(b^2-4*a*c)^1/2)/2*a;
z=(-b+(b^2-4*a*c)^1/2)/2*a;至
q=(-b-(b^2-4*a*c)^1/2)/2/a;
z=(-b+(b^2-4*a*c)^1/2)/2/a;在此之后,将b^2更改为b*b (^为xor,而不是power),将b^1/2更改为sqrt(b)。
然后,使用double而不是int。
发布于 2011-12-18 23:34:36
^符号实际上是bitwise XOR运算符,而不是幂或指数运算符,所以b^2实际上是b xor 2。请尝试使用b*b。
如果需要将基数提升到2以外的幂指数,则需要使用pow函数。
并使用sqrt函数(在<math.h>中)来计算平方根,而不是将数字提升到1/2的幂。
此外,a/b*c被解析为(a/b)*c,因此您需要使用以下两个括号之一:
(...)/(2*a);或者做第二次除法:
(...)/2/a;发布于 2011-12-18 23:36:11
首先,将所有数据类型更改为double,否则1/2将提供0而不是0.5。
其次,使用<cmath>头文件中的std::sqrt。
然后回想一下公式,并正确计算它。
https://stackoverflow.com/questions/8552744
复制相似问题