匿名用户
1级
2015-05-24 回答
我只能告诉你double 的20.6=20.600...001所以exchange=3.999...,而你的num又是int型的,当i=6时,最后除出来的结果是num[]={0,0,0,0,0,0,3}所以都不会提示你有没有一角零钱。所以你要解决的问题就是int 和double相除时造成的数据不准确,我的办法很土,就是在计算exchange的时候加上一个很小的数,帮你改成了下面的样子,你再试试
#include"stdio.h"
main()
{
double a[] = { 50,20,10,5,1,0.5,0.1 };
int num[7];
int i, pd;
double price, paid, exchange, rest;
printf("请输入商品总价:");
scanf("%lf", &price);
printf("请输入支付金额:");
scanf("%lf", &paid);
exchange = paid - price+1e-6;
rest = exchange;
for (i = 0;i<7;i++)
{
num[i] = rest / (a[i]);
rest -= num[i] * (a[i]);
}
if ((num[6]>3) && (num[6]<5))
{
printf("请问您有没有多余的0.1元?(1表示有,0表示没有)");
scanf("%d", &pd);
if (pd == 1)
{
exchange += 0.1;
rest = exchange;
for (i = 0;i<7;i++)
{
num[i] = rest / a[i];
rest -= num[i] * a[i];
}
}
}
if ((num[4]>3) && (num[4]<5))
{
printf("请问您有没有多余的1元?(1表示有,0表示没有)");
scanf("%d", &pd);
if (pd == 1)
{
exchange += 1;
rest = exchange;
for (i = 0;i<7;i++)
{
num[i] = rest / a[i];
rest -= num[i] * a[i];
}
}
}
printf("找零=");
for (i = 0;i<7;i++)
{
if (num[i] == 0)continue;
printf("%.1lf*%d(张)", a[i], num[i]);
}
}