神秘的 For 循环错误
我正在使用 Ubuntu 10.10、Codeblocks IDE 和 gcc 编译器。我注意到我正在编写的程序正在创建一些奇怪的输出。最终我将问题范围缩小到程序中的 for 循环。我惊讶地发现以下基本 for 循环没有按预期执行。
#include <iostream>
using namespace std;
int main()
{
for(unsigned int i = 0; i < 21; i++)
{
cout << i << endl;
}
return 0;
}
当我编译并运行它时,输出是:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
尽管人们期望输出应该包括零。非常令人惊讶的是,当我将 for 循环更改为时,
#include <iostream>
using namespace std;
int main()
{
for(unsigned int i = 0; i < 20; i++)
{
cout << i << endl;
}
return 0;
}
我得到了预期的输出:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
我一生都无法弄清楚为什么 21 (以及所有大于 21 的数字)给我这个错误的输出,而 20 (以及更低的数字) ) 不。如果有人以前遇到过类似的事情,我肯定很高兴听到他/她如何解决这个问题。
I am using Ubuntu 10.10, Codeblocks IDE, and gcc compiler. I noticed the program I am writing was creating some odd output. Eventually I narrowed the issue down to a for-loop in the program. I was surprised to discover that the following basic for-loop didn't perform as expected.
#include <iostream>
using namespace std;
int main()
{
for(unsigned int i = 0; i < 21; i++)
{
cout << i << endl;
}
return 0;
}
When I compile and run it, the output is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Although one would expect the output should include zero. Very surprisingly, when I change the for loop to
#include <iostream>
using namespace std;
int main()
{
for(unsigned int i = 0; i < 20; i++)
{
cout << i << endl;
}
return 0;
}
I get the expected output of:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
I can't for the life of me figure out why 21 (and all numbers greater than 21) give me this false output, while 20 (and lower numbers) don't. If anyone has run into anything like this before, I'd sure appreciate hearing how he/she worked around it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许屏幕只是滚动?
尝试将输出重定向到文本文件
maybe the screen just scroll?
try to redirect the output to a text file
这看起来很奇怪,我运行了你的第一个程序并得到了我所期望的结果:
但是,我注意到你使用 gcc 作为编译器。这是针对 C 编程的。最好像我一样使用 g++。这里工作得很好。 (我实际上很惊讶 gcc 编译了这一点:/)
This seemed so weird that i run your first program and got what i would expect :
However, i notice that you use gcc as your compiler. This one is aimed towards c programming. Better use g++ as i did for this. It works fine here. (i'm actually surprised gcc compiles that :/)