【题目链接】
ybt 1012:计算多项式的值
OpenJudge NOI 1.3 07:计算多项式的值
【题目考点】
1. 计算表达式书写
了解*的运算优先级比+高。
了解()可以改变运算优先级
2. 输出浮点型量a保留x位小数
cout<<fixed<<setprecision(x)<<a;
printf("%.xf", a);
3. 浮点型量的精度
float 单精度浮点型,可以表示6~7位有效数字
double 双精度浮点型,可以表示15~16位有效数字
本题要输出小数点后7位,为保险起见,选用double类型
4.(扩展)秦九韶算法
【题解代码】
解法1:普通解法。使用cin, cout进行输入输出。
#include <bits/stdc++.h>
using namespace std;
int main()
{
double x, a, b, c, d;
cin>>x>>a>>b>>c>>d;
cout<<fixed<<setprecision(7)<<a*x*x*x+b*x*x+c*x+d;
return 0;
}
解法2:普通解法。使用scanf, printf进行输入输出
#include <bits/stdc++.h>
using namespace std;
int main()
{
double x, a, b, c, d;
scanf("%lf %lf %lf %lf %lf", &x, &a, &b, &c, &d);
printf("%.7f", a*x*x*x+b*x*x+c*x+d);
return 0;
}
解法3:使用秦九韶算法
- 可以减少相乘次数,也可以减少表达式长度
#include <bits/stdc++.h>
using namespace std;
int main()
{
double x, a, b, c, d;
cin>>x>>a>>b>>c>>d;
cout<<fixed<<setprecision(7)<<x*(x*(a*x+b)+c)+d;
return 0;
}