此代码解决了三次函数的根。抛开任何数学概念,我特别想做三次循环(因为它的立方体)。因此,用户将输入根的猜测,v THREE TIMES。
现在问题出现在FIRST DO-WHILE LOOP之后,变量v的值似乎没有超过用户重新输入SECOND和THIRD DO-WHILE LOOP的值。
请帮帮我们!
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const double R = 0.082054;
double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
return s;
}
int main()
{
double a,b,P,T,Tc;
cin >> a;
cin >> b;
cin >> P;
cin >> T;
double v,v1=0,fv,fv1,N,e; //FIRST DO-WHILE
int iteration = 0;
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
do
{
v = v1;
fv = f(a,b,P,T,v);
fv1 = fPrime(a,b,P,T,v);
if (fv1==0)
{
cout << "Math Error";
break;
}
v1 = v-(fv/fv1);
cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
iteration++;
}
while(iteration<N && abs(v1-v)>e);
cout << "The approximate root/solution is " << v1 << endl;
iteration = 0; //SECOND DO-WHILE
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
do
{
v = v1;
fv = f(a,b,P,T,v);
fv1 = fPrime(a,b,P,T,v);
if (fv1==0)
{
cout << "Math Error";
break;
}
v1 = v-(fv/fv1);
cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
iteration++;
}
while(iteration<N && abs(v1-v)>e);
cout << "The approximate root/solution is " << v1 << endl;
iteration = 0; //THIRD DO-WHILE
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
do
{
v = v1;
fv = f(a,b,P,T,v);
fv1 = fPrime(a,b,P,T,v);
if (fv1==0)
{
cout << "Math Error";
break;
}
v1 = v-(fv/fv1);
cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
iteration++;
}
while(iteration<N && abs(v1-v)>e);
cout << "The approximate root/solution is " << v1 << endl;
return 0;
}
答案 0 :(得分:0)
在我看来你的行'cin&gt;&gt; v;'在你的代码中没有意义,因为每次你读v时,你都会立即将v1的值分配给v,其中'v = v1'。所以你最初的猜测就丢失了。 此外,由于第二次执行的退出条件与第一次执行的退出条件相同,第二次执行只应执行一次,执行后的v值应等于v1 = v-fv / fv1,所以你永远不会得到一个与第一个值不同的v的新第二个值。