分数化小数(C++)
题目来自刘汝佳编著的《算法竞赛入门经典(第二版)》
题目:
输入整数a, b ,c, 输出a/b的小数形式,精确到小数点后c位,a, b ≤ 10^6, c ≤ 100。输入包含多组数据, 结束标记为a = b = c = 0。
答案如下
#include<iostream> #include<cmath> using namespace std; int main() { int a, b, c, m; int con[100]; cin >> a >> b >> c; while (a != 0 && b != 0 && c != 0) { cout << a / b << "."; m = a % b; for (int i = 0; i <= c; i++) { con[i] = m * 10 / b; m = m * 10 % b; } if (con[c] >= 5) { con[c - 1]++; for (int i = c - 1; i >= 0; i--) if (con[i] == 0 && con[i + 1] >= 5 && i - 1 >= 0) con[i - 1]++; } for (int i = 0; i < c; i++) cout << con[i] ; cout << endl; cin >> a >> b >> c; } return 0; }
不知道有木有大神想到更厉害的算法!!!