例14.1
解题思路:
1.输入一个双精度浮点数
2.用不同的格式化输出方式输出该数字
"%f"默认输出6位小数
"%.5f"指定输出5位小数
"%e"输出科学计数法表示
"%g"自动选择定点数或科学计数法表示
#include<iostream>
#include<cstdio>
using namespace std;
int main() {
double n;
cin >> n; // 输入一个双精度浮点数
printf("%f\n",n); // 格式化输出n,默认6位小数
printf("%.5f\n",n); // 格式化输出n,保留5位小数
printf("%e\n",n); // 格式化输出n,科学计数法表示
printf("%g\n",n); // 格式化输出n,定点数或科学计数法表示
return 0;
}
例14.2
和普通保留位数方法一样,区别见代码:
#include <bits/stdc++.h>
using namespace std;
int main(){
double x;
int y;
cin >> x >> y;
cout << fixed << setprecision(y) << x;
return 0;
}
例14.3
1.输入一个浮点数
2.判断浮点数的小数部分是否大于等于5
3.如果是,向上取整输出
4.如果不是,向下取整输出
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double f;
cin >> f; // 输入一个浮点数
if (int(f * 10) % 10 >= 5) // 判断浮点数的小数部分是否大于等于5
cout << ceil(f); // 如果是,向上取整输出
else
cout << floor(f); // 如果不是,向下取整输出
return 0;
}
练14.1
解题思路:
1.题目要求求出去掉一个最高分和一个最低分后的平均分。
2.根据题目给出的信息,可以得到以下等式:
6个人打分的平均分为9.6分,即69.6 = a + b + c + d + e + f (a、b、c、d、e、f分别代表6个评委的分数)
去掉一个最高分后的平均分为9.4分,即69.4 = a + b + c + d + e
去掉一个最低分后的平均分为9.8分,即6*9.8 = b + c + d + e + f
3。根据上述等式,可以求解出a、b、c、d、e、f的值。
4.根据题目要求,求出去掉一个最高分和一个最低分后的平均分,即(h = g - a - f) / 4。
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
double a, b, c, d, e, f, g, h;
// 计算6个人打分的总分
g = 6 * 9.6;
// 计算去掉一个最高分后的总分
a = 6 * 9.6 - 5 * 9.4;
// 计算去掉一个最低分后的总分
f = 6 * 9.6 - 5 * 9.8;
// 计算去掉一个最高分和一个最低分后的平均分
h = (g - a - f) / 4;
// 输出结果,保留两位小数
printf("%5.2f", h);
return 0;
}
练14.2
解题思路:
1.题目给出了男生和女生的人数,以及男生和女生的平均分。
2.根据题目要求,求出全体同学的平均分。
3.使用平均公式:(男生人数 * 男生平均分 + 女生人数 * 女生平均分) / (男生人数 + 女生人数)。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x, y;
double z;
cin >> x >> y; // 输入男生和女生的人数
z = (double)(x * 87 + y * 85) / (x + y); // 计算全体同学的平均分
cout << fixed << setprecision(4) << z; // 输出结果,保留4位小数
return 0;
}
练14.3
解题思路:
这道题用到小学奥数牛吃草的解题方法,对于本题的公式:
(x∗a−y∗b)/(a−b)
接下来,我们按公式写代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int x, a, y, b;
cin >> x >> a >> y >> b;
double z = (y * b - x * a) * 1.0 / (b - a);
cout << fixed << setprecision(2) << z << endl;
return 0;
}
练14.4
直接根据公式写代码即可
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double a, b, c, d, x, f;
cin >> x >> a >> b >> c >> d; // 输入x和参数a、b、c、d的值
f = a * x * x * x + b * x * x + c * x + d; // 计算多项式f(x)的值
cout << fixed << setprecision(7) << f << endl; // 输出结果,保留到小数点后7位
return 0;
}