Re: [問題] 小新手程式寫不出來,麻煩高手幫忙。
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
double a,b,c,z1,z2,z3,z2i,z3i,sita;
cout<<" This program finds the roots of x^3 +a x^2 + b x + c =0 "<<endl;
cout<<" Enter the coefficient a: "; cin>>a;
cout<<" Enter the coefficient b: "; cin>>b;
cout<<" Enter the constant c: "; cin>>c;
double Q=(3*b*b-a*a)/9;
double R=(9*a*b-27*c-2*a*a*a)/54;
double D=(Q*Q*Q+R*R*R)/3;
if(D==0) {
z1 = -a/3+2*pow(R,1.0/3.0);
z2 = z3=-a/3+2*sqrt(-Q);
z2i=z3i=0;
}
if (D>0) {
z1 = -a/3+pow((R+sqrt(D)),1.0/3.0)+pow((R-sqrt(D)),1.0/3.0);
z2 = -a/3-(pow(R+sqrt(D),1.0/3.0)+pow(R-sqrt(D),1.0/3.0))/2;
z2i =(pow(R+sqrt(D),1.0/3)-pow(R-sqrt(D),1.0/3.0))*(sqrt(3)*0.5);
z3 = -a/3-(pow(R+sqrt(D),1.0/3.0)+pow(R-sqrt(D),1.0/3.0))/2;
z3i = -(pow(R+sqrt(D),1.0/3.0)-pow(R-sqrt(D),1.0/3.0))*(sqrt(3)*0.5);
}
if (D<0) {
double sita=acos(R/sqrt(-Q*Q*Q));
z1=-a/3+2*sqrt(-Q)*cos(sita/3);
z2=-a/3+2*sqrt(-Q)*cos(sita/3+2*M_PI/3);
z3=-a/3+2*sqrt(-Q)*cos(sita/3+4*M_PI/3);
z2i=z3i=0;
}
cout<<endl;
cout<<" "<<"x^3+"<<a<<" x^2+ "<<b<<" x+ "<<c<<" = 0"<<endl;
cout<<" Root 1: "<<z1<<endl;
cout<<" Root 2: "<<z2<<" + "<<z2i<<"i"<<endl;
cout<<" Root 3: "<<z3<<" + "<<z3i<<"i"<<endl;
system("pause");
return 0;
}
這是最新改好的,
跑出來還是不對,
結果都會寫啥#IND的,
都不是答案,
不過如果a=b=c=0
會算隊就是@@
可以再幫幫忙嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.218.123
噓
10/06 23:21, , 1F
10/06 23:21, 1F
→
10/06 23:21, , 2F
10/06 23:21, 2F
→
10/06 23:42, , 3F
10/06 23:42, 3F
噓
10/07 22:17, , 4F
10/07 22:17, 4F
→
10/07 22:34, , 5F
10/07 22:34, 5F
推
10/08 07:18, , 6F
10/08 07:18, 6F
→
10/08 08:26, , 7F
10/08 08:26, 7F
→
10/08 13:35, , 8F
10/08 13:35, 8F
討論串 (同標題文章)
完整討論串 (本文為第 3 之 4 篇):