题目链接
思路:先将前四次时间按照升序排序。
后三次时间的和如果小于给出的标准3,那么就inf,如果前三次的和大于标准时间 3那么就impossible,第三种情况就是,用标准时间 * 3 - 第二长时间和第三长时间。
主要是需要注意浮点数运算误差,要用整数代替运算,注意,如果直接用浮点数 *100 来运算会导致数值异常,下面给出两种将浮点数处理的方法
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
int main(){
int x[4],k,a,b;
for(int i = 0; i < 4; i++){
double temp;
cin>>temp;
x[i] = temp * 1000 / 10;
}
sort(x,x + 4);
double temp;
cin>>temp;
k = temp * 1000 / 10;//如果一定要用乘法直接转化浮点数需要多乘以10再除去,防止数据丢失
if(k * 3 >= x[1] + x[2] + x[3]){
printf("infinite\n");
}
else if(k * 3 < x[0] + x[1] + x[2]){
printf("impossible\n");
}
else{
int ans = k * 3 - x[1] - x[2];
printf("%.2lf\n",ans / 100.0);
}
return 0;
}
给出第二种方法
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
int main(){
int x[4],k,a,b;
for(int i = 0; i < 4; i++){
scanf("%d.%d",&a,&b);
x[i] = 100 * a + b;
}
sort(x,x + 4);
scanf("%d.%d",&a,&b);
k = a * 100 + b;
if(k * 3 >= x[1] + x[2] + x[3]){
printf("infinite\n");
}
else if(k * 3 < x[0] + x[1] + x[2]){
printf("impossible\n");
}
else{
int ans = k * 3 - x[1] - x[2];
printf("%.2lf\n",ans / 100.0);
}
return 0;
}