工大后院

 找回密码
 加入后院

扫一扫,访问微社区

QQ登录

只需一步,快速开始

搜索
查看: 2012|回复: 3

C语言简单问题

[复制链接]
发表于 2009-10-8 00:49 | 显示全部楼层 |阅读模式
刚学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)?
纯粹路过...
回复

使用道具 举报

发表于 2009-10-8 14:34 | 显示全部楼层
应该是浮点数的问题吧,浮点数有不少“莫名其妙”的计算错误的
回复

使用道具 举报

发表于 2009-10-8 17:56 | 显示全部楼层
应该是浮点数的问题,0.1和0.2都无法在二进制序列中精确表示。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 加入后院

本版积分规则

QQ|Archiver|手机版|小黑屋|广告业务Q|工大后院 ( 粤ICP备10013660号 )

GMT+8, 2024-5-14 08:06

Powered by Discuz! X3.5

Copyright © 2001-2024 Tencent Cloud.

快速回复 返回顶部 返回列表