HDU-鹽水的故事
阿新 • • 發佈:2019-06-24
http://acm.hdu.edu.cn/showproblem.php?pid=1408
這是一道高精度問題:
在自己錯了數十遍之後找到了不少規律:
首先是Output limit exceeded:之前一直不知道是什麼意思,現在才知道是輸入輸出的精度有問題
1 /* */ 2 # include <bits/stdc++.h> 3 using namespace std; 4 5 int main() 6 { 7 long long int VUL, D, i, t, f; 8 while( ~ scanf("%lld %lld", &VUL, &D) ) 9 { 10 t=0; 11 for( i=1; ; i++ ) 12 { 13 f = i*D; 14 if( VUL>f ) 15 { 16 t += i; 17 t += 1; 18 } 19 else if( VUL==f ) 20 { 21 t += i; 22 break; 23 } 24 else 25 { 26 if( VUL%D==0 ) 27 { 28 t += VUL/D; 29 break; 30 } 31 else 32 { 33 t += VUL/D+1; 34 break; 35 } 36 } 37 VUL = VUL - i * D; 38 } 39 printf("%lld\n", t); 40 } 41 return 0; 42 }
然後就是中間程式碼的精度問題了:
記住比較大小時,double型別跟double型別的比,int型別跟int型別的比,double要是跟int型別的比會有精度缺失
以下是AC程式碼:
1 /* */ 2 # include <bits/stdc++.h> 3 using namespace std; 4 5 int main() 6 { 7 long long int i, t; 8 double VUL, D, f; 9 while( ~ scanf("%lf %lf", &VUL, &D) ) 10 { 11 t=0; 12 for( i=1; ; i++ ) 13 { 14 int p = (int)(VUL/D);///double 型別求餘數 15 double r = VUL - p * D;///double 型別求餘數 16 f = i*D*1.0; 17 if( VUL>f ) 18 { 19 t += i; 20 t += 1; 21 } 22 else if( VUL==f ) 23 { 24 t += i; 25 break; 26 } 27 else if( r>=0.000001 )///不能跟0比,(即不能用r>0來判) 28 { 29 t += p+1; 30 break; 31 } 32 else 33 { 34 t += p; 35 break; 36 } 37 VUL = VUL - f; 38 } 39 printf("%lld\n", t); 40 } 41 return 0; 42 }
注意觀察以下WA程式碼和上面的AC程式碼:可以發現(r==0.000000)是錯誤的,是不是0.000000==0呀,它也是int型別的?(歡迎大佬評論)
1 /* */ 2 # include <bits/stdc++.h> 3 using namespace std; 4 5 int main() 6 { 7 long long int i, t; 8 double VUL, D, f; 9 while( ~ scanf("%lf %lf", &VUL, &D) ) 10 { 11 t=0; 12 for( i=1; ; i++ ) 13 { 14 int p = (int)(VUL/D); 15 double r = VUL - p * D; 16 f = i*D*1.0; 17 if( VUL>f ) 18 { 19 t += i; 20 t += 1; 21 } 22 else if( VUL==f ) 23 { 24 t += i; 25 break; 26 } 27 else if( r==0.000000 ) 28 { 29 t += p; 30 break; 31 } 32 else 33 { 34 t += p+1; 35 break; 36 } 37 VUL = VUL - f; 38 } 39 printf("%lld\n", t); 40 } 41 return 0; 42 }
PS.另一種AC程式碼:
1 #include<stdio.h> 2 int main() 3 { 4 double v,d; 5 long long int t; 6 while(scanf("%lf%lf",&v,&d)!=EOF) 7 { 8 int i; 9 t=0; 10 for(i=1;; i++) 11 { 12 if(v-i*d<=0) 13 { 14 while(v>0.0000001)/*v與0比較的話就WA了,因為d可能很小很小,而d無論多小,v只要剩下就得算*/ 15 { 16 v=v-d; 17 t++; 18 } 19 break; 20 } 21 v=v-i*d; 22 t=t+i; 23 t++; 24 25 } 26 printf("%lld\n",t); 27 } 28 return 0; 29 }View Code
&n