前言:核心思想就是模拟手算的除法
我的思想:使用数组将小数部分存储,输入c位,计算c+1,判断是否需要舍入。 考虑了 小数位为99999
的情况,所以使用数组存储而不是直接输出的方法更安全。
ps:我并不知晓使用数组是否有必要,希望能有好心人告知,不胜感激
此代码苦于没有找到可以提交的地方,若有同学看到,希望能帮我提交一下并告知,感激不尽!
/*
输入样例:
1 6 4
2 3 1
2 3 2
2 3 3
1 7 1
1 7 2
1 7 3
1 7 4
1 7 20
0 0 0
*/
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int a,b,n,kase=0;
int arr[101]={0};
while(cin>>a>>b>>n && b)
{
if(kase) printf("\n");
printf("Case %d: ",++kase);
memset(arr,0,sizeof(arr)); //数组初始化
int pos=1; //数组初始化
if(n==0)
printf("%d\n",a/b);
else
{
arr[0]=a/b;
int temp=a%b;//余数
int last=0; //n位的值
//接下来使用余数除以除数。
for(int i=0;i<=n;i++) //计算到 n+1位 用于舍入。
{
while(temp<b){ temp*=10; if(temp<b){ arr[pos]=0; pos++; i++;} }
if(i<n-1)
{
arr[pos]=temp/b;
pos++;
}
else if(i==n-1)
{
last = temp/b;
}
else //n+1位 用于舍入
{
if(temp/b >=5)
last+=1;
arr[pos]=last;
}
temp%=b;
}
for(int i=n;i>0;i--)
{
int carry=0;
if(arr[i]>9)
{
arr[i]=0;
carry=1;
}
if(carry)
{
arr[i-1] +=1;
}
}
}
cout<<arr[0]<<'.';
for(int i=1;i<=n;i++)
cout<<arr[i];
cout<<'\n';
}
return 0;
}
输出结果:
时隔四月, 重新复习这道问题,有了新的体会, 自然地写出了更简单的方法
//我的格式: for, while 中的+ - * / 不打空格。其余要打
//#define LOCAL
#include<stdio.h>
int main()
{
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int a, b, c, t, kase = 0;
while(scanf("%d%d%d",&a, &b, &c) == 3 && b != 0)
{
if(kase) printf("\n");
printf("Case %d: %d.", ++kase, a / b);
a %= b;
for(int i=0; i<c; i++)
{
if(a < b) a *= 10;
if(i < c - 1)
printf("%d", a / b);
else //最后一个单独处理进位
t = a / b;
a %= b;
}
a *= 10;
if( a / b >= 5)
t++;
printf("%d", t);
}
return 0;
}