習題2-9,分數化小數
阿新 • • 發佈:2019-02-03
輸入正整數a,b,c,輸出a/b的小數小數形式,精確到小數點後c位。a,b<=10^6,c<=100。例如a=1,b=6,c=4時應輸出0.1667。
這一題的難點是c的範圍(最大能到100),而我們所知的最大資料型別double也才只能精確到17位,所以只有一種選擇:自定義高精度運算。 但高精度運算是後面幾章的內容,怎麼會出現在這裡呢?還希望看到的朋友們幫忙回答,是不是我想落了什麼簡單的方法。#include <iostream> using namespace std; int main() { int a, b, c; cin >> a >> b >> c; int res[100 + 10]; for (int i = 0; i <= c + 1; ++i) { res[i] = a / b; a %= b; a *= 10; } if (res[c + 1] >= 5) { int carry = 1; for (int i = c; i >= 1; --i) { int s = res[i] + carry; carry = s / 10; res[i] = s % 10; } res[0] += carry; } cout << res[0]; if(c) cout << "."; for (int i = 1; i <= c; ++i) { cout << res[i]; } cout << "\n"; return 0; }
需要注意的一點是:不要忘了最後一位的四捨五入。