我无法为数组的元素赋值(使用:for 循环和嵌套的 if 语句)
I can't assign values to the elements of the array (using:for loop and nested if statement)
我试图将低于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;
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式