| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 4319 人关注过本帖
标题:当double类型强制转换为int时,百分位少了1,请教这是什么原因?
取消只看楼主 加入收藏
chuguoping
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2013-5-15
结帖率:100%
收藏
已结贴  问题点数:20 回复次数:3 
当double类型强制转换为int时,百分位少了1,请教这是什么原因?
这是我在自学《c语言入门经典》时遇到的问题,第二章习题3:一个产品有两个版本,其一价格为$3.5,其一价格为$5.5(本人修改为3.55和5.55),编写一个程序提示用户输入产品版本和数量,然后根据产品数量,计算并输出价格。——因为该书习题4是要求以“** dollars and ** cents”的格式输出某工人的时薪,所以我结合起来写到:
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int quantity = 0;
    const double prince_1 = 3.55;
    const double prince_2 = 5.55;
    int type = 0;
    double total = 0.0;
    double cents = 0.0;
    int k = 0;

    printf("Input the type of book is 1 or 2?\n");
    scanf("%d",&type);
    printf("Input the quantity of books are :");
    scanf("%d",&quantity);

    total = quantity*(prince_1+(type-1)*(prince_2-prince_1));
    printf("\nThe total are %.5f\n",total);
    cents = total-(int)total;/*这一段是为了看清楚哪步出了问题,才拆开写的*/
    printf("%f\n",cents);
    cents = 100*(total-(int)total);
    printf("%f\n",cents);
    k = (int)cents;

    printf("\n\n %d dollars and %d cents",(int)total,k);

    return 0;
}

可是在我输入产品为1,数量为32时,明明应该是$113.60

输出的却是113 dollars and 59 cents

请问这是为什么?
图片附件: 游客没有浏览图片的权限,请 登录注册
搜索更多相关主题的帖子: 产品 价格 quantity dollars include 
2013-05-15 20:55
chuguoping
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2013-5-15
收藏
得分:0 
回复 2楼 Ryker
没跳过啊,可能是自学得不够仔细吧。
2013-05-16 11:14
chuguoping
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2013-5-15
收藏
得分:0 
回复 4楼 邓士林
感谢版主回复,请教这种问题该如何避免或修正呢?
2013-05-16 11:15
chuguoping
Rank: 1
等 级:新手上路
帖 子:8
专家分:0
注 册:2013-5-15
收藏
得分:0 
回复 3楼 笑傲
谢谢,请教该如何修改程序才能避免这类问题,或者说在今后遇到类似的问题该如何处理?——有这方面专题的文章可以推荐吗?
2013-05-16 11:17
快速回复:当double类型强制转换为int时,百分位少了1,请教这是什么原因?
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.017888 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved