为什么这段代码会出界错误?

时间:2020-04-13 14:13:31

标签: c++ arrays stl c++14 c++17

我一直在尝试理解以下代码的超出范围的错误,但我无法弄清楚。最初的问题是https://codeforces.com/contest/148/problem/A。我不知道为什么会被卡住,您能告诉我如何避免类似类型的错误。

  #include <iostream>
  using namespace std;
  int main()
  {
    std::ios::sync_with_stdio(false);
    int k,l,m,n,d,count=0;

    cin>>k>>l>>m>>n>>d;
    int arr[d]={0}; 

    for (int i = 0; i < d; ++i){
      int k1=k*(i+1); k1--;
      int l1=l*(i+1); l1--;
      int m1=m*(i+1); m1--;
      int n1=n*(i+1); n1--;

      if(arr[k1]==0 && k1<d){
        arr[k1]=1; count++;
      }
      if(arr[l1]==0 && l1<d){
        arr[l1]=1; count++;
      }
      if(arr[m1]==0 && m1<d){
        arr[m1]=1; count++;
      }
      if(arr[n1]==0 && n1<d){
        arr[n1]=1; count++;
      }

    }

    cout<<count;


    return 0;
  }

1 个答案:

答案 0 :(得分:1)

您需要首先在以下位置检查边界:

a, b, c, d = [tf.constant(i, name='constant_' + x) for i, x in zip(range(1, 5), 'abcd')]

具有:

if(arr[k1]==0 && k1<d)

如果第一个条件为假,则不会测试第二个条件。但是对方不是真的。第一个条件将始终被测试。