此代码顺利进行,直到我特意在DO-WHILE LOOP中包含一个包含BREAK的IF-STATEMENT,如果fv1 = 0(对于任何除以零的内容未定义),应该报告数学错误。但是,打印出了意想不到的结果。
#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()
{
//INPUT STAGE!
cout << "Use gas constant, R: " << R << endl;
double a,b,P,T,Tc;
cout << "\nUse test value, a: ";
cin >> a;
cout << "\nUse test value, b: ";
cin >> b;
cout << "\nUse pressure, P (atm): ";
cin >> P;
cout << "\nUse absolute temperature, T (K): ";
cin >> T;
double v,v1=0,fv,fv1,N,e;
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;
cout << "\n";
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);
return 0;
}
答案 0 :(得分:2)
break语句结束最近的封闭循环或条件语句的执行 -
顺便说一句,你将0分配给fv1。
使用
if (fv1 == 0)
或
if (0 == fv1)
答案 1 :(得分:2)
尝试更改条件从fv1=0
到fv1==0
这是赋值运算符=
而这是比较运算符==