数值计算方法,可以说是我大三上学得最认真的一门课,可惜我不会考试背不住3Q
第一章 Task1.多项式求解的秦久韶方法
#include#include using namespace std; //秦久韶算法实现 int Qin(int num[], int x,int n) { //num_in数组为a0,a1,...an是多项式系数 //x为多项式变量的具体值 //n为多项式阶数 int v = num[n-1]; //即令v=an,v是每一步累计的量 for (int k = 2; k <= n; k++) //循环n-1次 { v = x * v + num[n - k]; //核心,由内向外逐层计算一次多项式的值 } return v; //返回最终的累计量 } //主函数 int main() { int i = 0, n = 0, x; int num[1000]; //创建一个静态数组用来存放多项式系数 char c; cout << "请问是多项式几阶?" << endl; cin >> n; //想要存储的数的数目 cout << "请依次输入多项式系数(以空格分隔):" << endl; while (i < n) { c = getchar(); //获取输入字符 if ((c >= '0'&&c <= '9') || c == '-') //输入正整数、负整数 { ungetc(c, stdin); cin >> num[i++]; } } cout << "请问x为?" << endl; cin >> x; cout <<"答案是:"< Task2.一元二次方程求根公式
#includeTask3.方程求根的二分法#include using namespace std; //一元二次方程求根公式算法实现 void solvefunction(double c,double b) { double d = b * b - c; //delta double x1=0.0, x2=0.0; //根 if (d < 0) { cout << "**无实根**" << endl; } else if (d == 0) { //x1 = -b;测试证明,这样计算也容易出现大数吃小数的问题 x1 = sqrt(c); //改变计算方法 cout << "x1 = x2 = " << x1 << endl; } else { if (b >= 0.) { x1 = -b - sqrt(d); } else { x1 = -b + sqrt(d); } } x2 = c / x1; cout << "x1 = " << x1 << endl; cout << "x2 = " << x2 << endl; } //主函数 int main() { double large = 1e9; //大数10^9 double small = 1.0; //小数1 double c = large; //方程中的c值 double b = -(large + small) / 2.0;//方程中的b值。不准,但是可以用来算绝对值较大的根 solvefunction(c, b); system(" "); return 0; }
#include#include #include using namespace std; double ans_x; //x最终输出答案设置为全局变量 double ans_y; //y最终输出答案设置为全局变量 double f(int T, double x) //题目给出的函数,添加变量T(type)指定是哪一题的方程 { switch (T) { case 1: return x * x * x - x - 1; //习题一的方程 break; case 2: return exp(x) + 10 * x - 2;//习题二的方程 break; default: cout << "error" << endl; break; } } //二分法算法实现 void m(int T, double a, double b,double e)//T:题号,[a,b]初始区间,e精确度 { double x = (a + b) / 2; double y0 = f(T,a); double y = f(T,x); if (fabs((b-a)/2.0) < e) { ans_x = x; ans_y = y; return; } if (y0*y <= 0) m(T,a, x,e); //递归 else m(T,x, b,e); } //主函数 int main() { m(1,1, 2,1e-3); cout << "习题1.二分法算x^3-x-1=0在[1,2]内误差不超过10^-3的近似根是:" << endl; cout <<"x="<



