我无法为数组的元素赋值(使用:for 循环和嵌套的 if 语句)

I can't assign values to the elements of the array (using:for loop and nested if statement)

本文关键字:for 循环 嵌套 语句 if 数组 元素 赋值 使用      更新时间:2023-10-16

我试图将低于10的数字分配给数组,这些数字是3的倍数,但不知何故我得到了一些大数字(AKA-Errors)。我的循环不起作用。你能告诉我我错在哪里以及如何解决它吗?

下面是我的代码:

#include <iostream>
using namespace std;
int main() {
    int i = -1;
    int arr[10];
    for ( int x = 1; x < 10; x++, i++)
    {
        if (x % 3 == 0)
        {
            arr[i + 1] = x;
        }
    }
    cout << arr[0] << endl << arr[1] << endl<< arr[3] << endl;
}

如果我在"If"循环中添加cout << x;,它会输出它们,但它可能根本不分配它们。我想不明白。

任何想法?

至少像

那样改变循环
for ( int x = 1; x < 10; x++)
{
    if (x % 3 == 0)
    {
        arr[++i] = x;
    }
}

否则i的变化是变量x的9倍,并且数组有孔

[i+1]改为[++i]

第一个不改变i的值,所以每次你赋值给第一个数组项。(索引0)

//编辑:我没有意识到你在每个for循环上增加i,但正如我的追随者所说,你应该删除它。

对不起,你的代码一点意义都没有。

为什么以int i = -1开头?如果你只想要3个值,为什么要声明一个大小为10的数组?

如果你想加能被3整除的数,你不需要模计算。你所要做的就是从0(或3)开始,然后把它们相加。然而,我想这是一种练习,所以我们按你的方式来做。

#include <iostream>
int main(){
  int arr[10];
  int x = 0; //we will check whether x is dividable by 3 or not
  for( int i = 0; i < 10; x++ ){ // note that we increment x here
    if( x % 3 == 0 ){
      arr[i] = x;
      i++; // now we increment x i.e. next time we fill in the next array element
    }
  }
  //print array
  for( int i = 0; i < 10; i++ ){
    std::cout << "arr["<< i << "] = " << arr[i] << std::endl;
  }
  return 0;
}