输入两个正整数n<m<10^6,输出++ · · · +,保留5位小数。输入包含多组数据。结束标记位 n = m = 0。
样例输入:
2 4
65536 655360
0 0
样例输出:
Case 1: 0.42361
Case 2: 0.00001
代码如下:
#include<stdio.h>
#include<math.h>
int main(){
long long n;
int m, count = 0;
double num = 0, sum = 0;
while(scanf("%d%d", &n, &m)&& bool(n + m) == 1){
// bool()将n+m转为bool类型,且通常所有非零值都为true
// 所以我们将bool(n + m) == 1 作为判定是否结束while循环的条件
// 与条件中结束标记位 n = m = 0相符合
for(int i = 0; i <= m - n; i++){
num = 1 / pow((n+i), 2);
sum += num;
}
count++;
}
for(int i = 1; i <= count; i++){
printf("Case %d : %.5f\n", i, sum);
}
}
这里我们的 n 如果用 int 类型,则会在使用 pow() 函数计算65536 655360时产生数据溢出,所以在上方的代码我用了 long long 类型。
同样我们也可以不使用 long long 类型,做逐步除法代码如下:
num = 1 / (n + i)/(n + i);
这样子我们所写的<math.h>头文件就没有用了,可以删除掉,提高效率。
C++解法代码如下:
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
long long n;
int m, count = 0;
double num = 0, sum = 0;
while (cin >> n >> m && bool(n + m) == 1) {
for(int i = 0; i <= m - n; i++){
num = 1 / pow((n+i), 2);
sum += num;
}
count++;
}
cout.setf(ios::fixed);
for(int i = 1; i <= count; i++){
cout <<"Case "<< i << ": " << setprecision(5) << sum << endl;
}
return 0;
}
这里我们用到了C++中的标准库iomanip中的setprecision,
setprecision(n) | 设置浮点数的有效数字为n位 |
这里就简单介绍一下
#include<iostream>
#include<iomanip>
using namespace std;
int main() {
float a = 0.201;
cout.setf(ios::fixed); // 第一段
cout << "a = " << setprecision(2) << a << endl; // 第二段
// cout << "a = " << fixed << setprecision(2) << a << endl; // 第三段
return 0;
}
运行第一、二段结果为:
保留了最后一位0,因为我们再前设置了cout.setf(ios::fixed)——用定点格式显示浮点数
单独运行第二段为:
会省掉0,因为 setprecision(2) 设置浮点数的有效数字为2位,所以省掉0
第三段结果为:
同样保留了0,使因为cout<<fixed是用一般的方式输出浮点型
知识不足所以解释的不好,希望你们有更好的解释