C++实现Newton-Rhapson方法遇编译错误:expected primary-expression
解决Newton-Rhapson方法代码的编译错误及优化建议
编译错误的直接原因
你遇到的expected primary-expression before ‘<<’ token错误,根源在于宏定义末尾多余的分号:
#define f(x) (0.95 * pow(x, 3.0) - 5.9 * pow(x, 2.0) + 10.9 * x - 6.0); #define g(x) (2.85 * pow(x, 2.0) - 11.8 * x -+ 10.9);
宏是纯文本替换,当你在cout语句中调用f(x1)时,会被展开成:
(0.95 * pow(x1, 3.0) - 5.9 * pow(x1, 2.0) + 10.9 * x1 - 6.0); << endl;
这里的分号会直接中断cout的链式输出,导致语法错误。
第一步:修正宏定义
去掉宏末尾的分号,同时修正g(x)里的笔误-+为+(否则导数计算错误会影响迭代收敛):
#define f(x) (0.95 * pow(x, 3.0) - 5.9 * pow(x, 2.0) + 10.9 * x - 6.0) #define g(x) (2.85 * pow(x, 2.0) - 11.8 * x + 10.9)
其他需要修正的问题
- 输入提示拼写错误:
Agergar error tolerable:→Agregar error tolerable:Agragar iteracion maxima:→Agregar iteracion maxima:
- 浮点函数匹配问题:
你使用float类型,但fabs默认处理double,建议改用fabsf,或者直接将变量类型换成double(数值计算中double精度更常用)。 - 宏的潜在风险:
宏容易引发优先级或参数副作用问题,推荐改用inline函数替代宏,代码更安全易读:inline double f(double x) { return 0.95 * pow(x, 3.0) - 5.9 * pow(x, 2.0) + 10.9 * x - 6.0; } inline double g(double x) { return 2.85 * pow(x, 2.0) - 11.8 * x + 10.9; }
修正后的完整代码
#include <iostream> #include <iomanip> #include <cmath> #include <cstdlib> inline double f(double x) { return 0.95 * pow(x, 3.0) - 5.9 * pow(x, 2.0) + 10.9 * x - 6.0; } inline double g(double x) { return 2.85 * pow(x, 2.0) - 11.8 * x + 10.9; } using namespace std; int main () { double x0, x1, f0, f1, g0, e; int step = 1, N; cout << setprecision(6) << fixed; cout << "Agregar estimación inicial: "; cin >> x0; cout << "Agregar error tolerable: "; cin >> e; cout << "Agregar iteracion maxima: "; cin >> N; cout << endl << "*******" << endl; cout << "Metodo Newton Raphson " << endl; cout << "*******" << endl; do { g0 = g(x0); f0 = f(x0); if (g0 == 0.0) { cout << "Error matematico."; exit(0); } x1 = x0 - f0 / g0; cout << "iteracion-" << step << ":\t x = " << setw(10) << x1 << " y f(x) = " << setw(10) << f(x1) << endl; x0 = x1; step++; if (step > N) { cout << "No Convergente."; exit(0); } f1 = f(x1); } while (fabs(f1) > e); cout << endl << "Raiz: " << x1; return 0; }
内容的提问来源于stack exchange,提问作者Santiago Guzmán
相关产品推荐
相关产品推荐

