[英]For loop - more in output than needed
Well all I had to do was:好吧,我所要做的就是:
Example :例子 :
User enters:用户输入:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,4
Output should be:输出应该是:
1,2,3
according to me, my output is correct.据我说,我的输出是正确的。 But after 1,2,3 alot of 0 come in.
但是在 1,2,3 之后,很多 0 进来了。
#include <iostream>
using namespace std;
int i,skaitlis,sk2,x;
int masivs[19];
int main() {
for ( i=0; i<=19; i++ )
{
cin >> masivs[i];
skaitlis = masivs[19];
}
for (i=0;i < sizeof masivs; i++){
if ( masivs[i]<skaitlis){
cout << masivs[i] <<endl;
}
}
}
The problem is here:问题在这里:
for (i=0;i < sizeof masivs; i++){
The sizeof
operator returns the size of the array in bytes , not in number of elements. sizeof
运算符以字节为单位返回数组的大小,而不是以元素数为单位。 On normal modern systems the size of an int
is four bytes, meaning sizeof masivs
will give you 4*19
.在普通的现代系统上,
int
的大小是四个字节,这意味着sizeof masivs
将为您提供4*19
。
That will lead the loop going massively out of bounds and give you undefined behavior .这将导致循环大量超出范围并给您未定义的行为。
Not to mention the other out of bounds you have in the previous loop.更不用说你在上一个循环中的另一个越界了。
Also, taking about the first loop, why have the assignment to skaitlis
inside the loop?另外,考虑第一个循环,为什么在循环内分配给
skaitlis
? After you fix the out-of-bounds indexing, it will just assign zero (because masivs
is a global variable and therefore initialized to all zeroes) except in the last iteration.在修复越界索引后,它只会分配零(因为
masivs
是一个全局变量,因此初始化为全零),除非在最后一次迭代中。 You can move that assignment to be outside the loop.您可以将该分配移到循环之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.