題目的 keep 和 dispose 是取決於 四捨五入前 的結果
而輸出前半段的 獲利率 是 四捨五入後 的結果
解法一、化成整數運算
🔹 浮點數誤差
浮點數誤差
一個著名的例子是 0.1 + 0.2 != 0.3
(0.30000000000000004)
誤差會導致四捨五入計算錯誤,例如
以下代碼對 四捨五入的預期結果為
但實際上輸出卻是
#include <bits/stdc++.h>
using namespace std;
int main(){
double x = 2.195;
cout << round(x*100)/100;
return 0;
}
試著輸出到小數點後 16 位
會發現 x
的值是
x
的誤差也就導致了後續四捨五入的計算錯誤
( 四捨五入 )
#include <bits/stdc++.h>
using namespace std;
int main(){
double x = 2.195;
cout << setprecision(17) << x;
return 0;
}
🔹 用整數運算避免誤差
在整數手動完成四捨五入
(x*1000 確保要小數點後三位都在整數位)
✅ 完整代碼
評分結果(參考) : AC (3ms, 336KB)
#include <bits/stdc++.h>
using namespace std;
int main(){
int n, m, p;
cin >> n;
for(int i=0; i<n; i++){
scanf("%d %d", &m, &p);
double x = (p-m)*100.0 / m;
double fixed = (int)((x*1000+(x>0?5:-5)) / 10) / 100.0;
printf("%.2f%% ", fixed);
if(x >= 10 || x <= -7) printf("dispose\n");
else printf("keep\n");
}
return 0;
}