Chinaunix首页 | 论坛 | 博客
  • 博客访问: 313480
  • 博文数量: 45
  • 博客积分: 2079
  • 博客等级: 上尉
  • 技术积分: 464
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-03 16:57
文章分类

全部博文(45)

文章存档

2015年(1)

2013年(1)

2012年(9)

2011年(2)

2010年(32)

分类: C/C++

2012-02-23 16:38:20

先从一段计算百分比的代码说起。

1 #include
2 int main()
3 {
4     int count = 1;
5     int total = 11;
6     float percent = 0;
7     percent = (float)(count * 100 )/total;
8     printf("percentage is %.2f\n",percent);
9     return 0;
10 }

[root@localhost test]# gcc test_float2.c             
[root@localhost test]# ./a.out
percentage is 9.09

OK,结果正确,貌似没有问题,其实不然,我们把数字放大再看看结果吧。

4     int count = 100000000; //一亿
5     int total = 1100000000; //11亿

percentage is 1.28

奇怪了,同样的比例,为啥结果不一样呢?细心的朋友肯定早就发现了,第7行count先乘了100,当count*100值大于2147483647(21亿多)时,发生了整形溢出。

修改成:

7     percent = ((float)count/total)*100;

percentage is 9.09

另外,为什么发生溢出的结果是1.28呢,让我们来算一下:

100亿对应的二进制数是:10 01010100 00001011 11100100 00000000,一个34位,溢出了两位,符号位为0,所以溢出之后得到的结果是01010100 00001011 11100100 00000000,换算成十进制数是1410065408,这个数除以1100000000,取两位有效数字,得1.28。

阅读(1219) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~