为什么会停下来?

nl_eve 2009-03-03 01:42:28
/* HELLO.C -- Hello, world */

#include "stdio.h"
#include "conio.h"

void main()
{
int i=1;
while(i>0)
{
i++;
printf("loop!\n");
}
printf("It is the end of the program.");
getch();
return;

}


这个程序为什么不是一直出现LOOP,而会停下来。
...全文
63 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
zcbenniao 2009-03-03
  • 打赏
  • 举报
回复
int i = 32767;
i+1 是-32768
ctan 2009-03-03
  • 打赏
  • 举报
回复
i++发生溢出时会停下来
xxweilw 2009-03-03
  • 打赏
  • 举报
回复
如果想不停的话,直接去掉i++;吧
liangchaowei829 2009-03-03
  • 打赏
  • 举报
回复
学习了
Pikoona 2009-03-03
  • 打赏
  • 举报
回复

会中断的。

当i为整形的最大值时,加1,就产生了回绕,不再大于0了。

即0x7FFFFFFF+1>0不成立。

修改代码如下:



#include <stdio.h>
#include <conio.h>

void main()
{
int i=0x7FFFFFF0;
while(i>0)
{
i++;
printf("i=%X!\n", i);
}
printf("It is the end of the program.");
getch();
return;

}



运行结果如下:

i=7FFFFFF1!
i=7FFFFFF2!
i=7FFFFFF3!
i=7FFFFFF4!
i=7FFFFFF5!
i=7FFFFFF6!
i=7FFFFFF7!
i=7FFFFFF8!
i=7FFFFFF9!
i=7FFFFFFA!
i=7FFFFFFB!
i=7FFFFFFC!
i=7FFFFFFD!
i=7FFFFFFE!
i=7FFFFFFF!
i=80000000!
It is the end of the program.


0x80000000是绝对值最大的负数,也就是最小的整数,当然小于0,所以退出循环。

不过从1加到0x7FFFFFFF,在每加一都打印输出的情况下,会需要很长的时间:
在我的机器上(P4 E2180)运行1分钟可以达到0x690000,加到0x7FFFFFFF要超过两个小时。
nl_eve 2009-03-03
  • 打赏
  • 举报
回复
我用的是WIN-TC
nl_eve 2009-03-03
  • 打赏
  • 举报
回复
一会儿就断了,出现了It is the end of the program
bingyang622 2009-03-03
  • 打赏
  • 举报
回复
运行多久断啊,我这没断啊

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧