這是大三閱讀《算法競賽入門經典第二版》時寫的,當時是為了準備算法題:
關于《算法競賽入門經典第二版》習題2-5分數化小數問題,網絡上有一些代碼
#include<stdio.h> int main(void) { int a, b, c; scanf("%d%d%d", &a, &b, &c); printf("%.*f\n", c, (double)a/b); return0; }
我發現采用格式化輸出的方法是不正確的,經過測試只能輸出16位左右,超出會自動補0
我采用模擬除法的過程,同時對最后一位四舍五入,代碼如下:
#include<iostream> using namespace std; int main() { int a,b,c,n,n1; while(scanf("%d",&a)&&scanf("%d",&b)&&scanf("%d",&c)&&(a||b||c)) { for(intcount=0;;count++) { if(count) if(count<=c) printf("%d",n); else { if(n1=a/b>=5) printf("%d",n+1); else printf("%d",n); break; } n=a/b; a=(a-n*b)*10; if(count==1) cout<<"."; } } return 0; }
經過測試,這才是正確的解答
程序運行結果如下:
Paste_Image.png