2-5 输入正整数a,b,c,输出a/b的小数形式,精确到小数点后c位。其中a,b ≤ 10^6, c≤100。输入包含多组数据,结束标记为a=b=c=0。
样例输入:
1 6 4
0 0 0
样例输出:
Case 1: 0.166
前16位
#include <iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
int main()
{
//16位
int a, b, c,count;
count = 0;
double aa;
while (scanf_s("%d%d%d",&a,&b,&c) != EOF)
{
count++;
if (a == 0 && b == 0 && c == 0)
{
break;
}
aa = double(a) / b;
//aa *= pow(10, c);
//aa = int(aa) / pow(10, c);
printf("Case %d : %.*lf", count,c, aa);
}
return 0;
}
如果需要更多位数采用模拟除法的方法:前c-1位写出c的后一位考虑四舍五入
#include <iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
int main()
{//more
int a, b, c, count, d;
count = 0;
double aa;
while (scanf_s("%d%d%d", &a, &b, &c) != EOF)
{
if (a == 0 && b == 0 && c == 0)
{
break;
}
count++;
printf("Case %d : %d.", count, a / b);
for (int i = 0; i < c - 1; i++)
{
a %= b;
a *= 10;
cout << a / b;
}
a %= b;
a *= 10;
d = a / b;
a %= b;
a *= 10;
if (a / b > 5)
{
cout << d + 1 << endl;
}
else
{
cout << d << endl;
}
}
return 0;
}