写codeforces(以下简称cf),883,Div3,D题时有数据范围求三角形面积,小数位精度,自己用的double,看到题解用的long double。单纯的变为long double后输出最终结果时发现有问题。下面是几种写法的本地运行结果,判题是否可以通过和原因。
cf的判题机选的这个
目录
1.Wi11,Devc++5.4.0,使用printf("%Lf\n",he);会输出乱码
3.题解使用的为cout,我将我的代码最后的printf("%Lf\n",he);单纯的改为cout<<<'\n';也会出现精度问题。编辑<>
4.将题解 看似无用的部分 删除(下面以注释代替删除)会发生和3一样的问题
1.Wi11,Devc++5.4.0,使用printf("%Lf\n",he);会输出乱码
完整代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;scanf("%d",&t);
while(t--){
int n,d,h;scanf("%d %d %d",&n,&d,&h);
int a[n+2];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
sort(a,a+n);
long double he=0;
he=(long double)d*h/2.0;
//printf("he=%lf\n",he);
for(int i=1;i<n;i++){
he+=(long double)d*h/2.0;
if(a[i]-a[i-1]<h){
int hh=h-(a[i]-a[i-1]);
long double dd=(d*1.0/h)*hh;
he-=(dd*hh)/2;
}
}
// cout<<he<<'\n';
printf("%Lf\n",he);
}
return 0;
}
/*
*/
本地运行样例截图,发现输出是乱码的,但在cf上提交是可以Accepted(以下简称AC)的,如图。
2,如何解决本地运行乱码的情况(我没解决)
别人的解决方案
我试了试,没用本地运行还是乱码,没搜到别的解决方案。但提交了也可以AC
3.题解使用的为cout,我将我的代码最后的printf("%Lf\n",he);单纯的改为cout<<he<<'\n';也会出现精度问题。
4.将题解 看似无用的部分 删除(下面以注释代替删除)会发生和3一样的问题
#include <bits/stdc++.h>
using namespace std;
int main() {
//ios::sync_with_stdio(false);
//cin.tie(nullptr);
//cout.tie(nullptr);
//cout.precision(10); cout.setf(ios::fixed);
int ttt;
cin >> ttt;
while (ttt--) {
int n, d, h;
cin >> n >> d >> h;
vector<int> y(n);
for(int i = 0; i < n; i++){
cin >> y[i];
}
long double ans = (long double)d * h / 2.0;
for (int i = 0; i + 1 < n; ++i) {
if (y[i + 1] >= y[i] + h) ans += (long double)d * h / 2.0;
else{
long double d2 = (long double)d * (y[i] + h - y[i + 1]) / h;
long double nh = y[i + 1] - y[i];
ans += (d + d2) / 2.0 * nh;
}
}
cout << ans << '\n';
}
return 0;
}
5.解释一下这几行看似无用的部分 有什么用
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cout.precision(10); cout.setf(ios::fixed);
前三行和本题long double输出关系不大,别人的解释
大概就是加速cin/cout的效率,但不能使用scanf和printf了(259条消息) 【C++】ios::sync_with_stdio(false) 与 cin.tie(nullptr) 加速 IO_idiot5lie的博客-CSDN博客(259条消息) 关于ios::sync_with_stdio(false);和 cin.tie(nullptr);_canger_的博客-CSDN博客
注释掉前三行也可以AC
第四行
cout.precision(10); cout.setf(ios::fixed);
std::setprecision、std::ios::fixed使用说明_荆楚闲人的博客-CSDN博客
总结
printf("%Lf\n",he);在win环境下本地用会乱码(提交后不影响判题)
cout要额外设置精度
写题时可以用printf("%lf\n",he);测试,提交时改回来。或者记住如何设置cout。