低调的MJ 发表于 2009-10-8 00:49

C语言简单问题

刚学C语言的表妹问我一个好简单的问题,题目和解决方法如下。有人知道为什么出现这种情况么?(个人认为编译器的编译规则问题)

You will write a coin-changing program for lab1. First, ask the user for the amount in
Hong Kong dollars, such as 56.30. Then find the minimum number of $10, $5, $2, $1, 50
cent, 20 cent, and 10 cent coins to give in return.
For example, your program first prompts the user for the amount in HKD by displaying the
following message.
Please input the amount in Hong Kong dollars:
If the input is 56.30, the output should be
10-dollar coin: 5
5-dollar coin: 1
2-dollar coin: 0
1-dollar coin: 1
50-cent coin: 0
20-cent coin: 1
10-cent coin: 1


代码(表妹写的比较浅显没注释,劳烦各位了):
#include<stdio.h>
int main()
{
    double a,b;
    int x,y,z,u,v,w,q;
    printf("please input the amount in Hong Kong dollar:");
    scanf("%lf",&a);
    x=(int)a/10;
    printf("10-dollar coin:%d\n",x);
    y=((int)a-x*10)/5;
    printf("5-dollar coin:%d\n",y);
    z=((int)a-x*10-y*5)/2;
    printf("2-dollar coin:%d\n",z);
    u=(int)a-x*10-y*5-z*2;
    printf("1-dollar coin:%d\n",u);
    b=a-(int)a;
    v=(int)(b/0.5);
    printf("50-cent coin:%d\n",v);
    w=(int)((b-(double)v*0.5)/0.2);      //改为/0.199999结果才会正确
    printf("20-cent coin:%d\n",w);
    q=(int)((b-v*0.5-w*0.2)/0.1);         //改为/0.099999结果才会正确
    printf("10-cent coin:%d\n",q);
    getch();
    return 0;
}

不会游泳鱼 发表于 2009-10-8 14:31

把除法换成乘法有没有帮助 (例如 /0.2 换成 *5)?
纯粹路过...

iptton 发表于 2009-10-8 14:34

应该是浮点数的问题吧,浮点数有不少“莫名其妙”的计算错误的

gyCai 发表于 2009-10-8 17:56

应该是浮点数的问题,0.1和0.2都无法在二进制序列中精确表示。
页: [1]
查看完整版本: C语言简单问题