阵列出现问题:/
Having trouble with Arrays :/
到目前为止,这是我的代码
int main()
{
srand(time(0));
int inputnum,occurrences;
occurrences = 0;
cout<<"Enter a number to check the occurences"<<endl;
cin>>inputnum;
int arrayofnum[10] = {(rand()%201),(rand()%201),(rand()%201),(rand()%201),(rand()%201),(rand()%201),(rand()%201),(rand()%201),(rand()%201),(rand()%201)} ;
cout<<arrayofnum[0]<<","<<arrayofnum[1]<<","<<arrayofnum[2]<<","<<arrayofnum[3]<<","<<arrayofnum[4]<<","<<arrayofnum[5]<<","<<arrayofnum[6]<<","<<arrayofnum[7]<<","<<arrayofnum[8]<<","<<arrayofnum[9]<<endl;
for(int i=1;i<=10;i++)
{
if(inputnum == arrayofnum[i])
occurrences++;
}
cout<<"The number of occurrences of "<<inputnum<<"in the random list is "<<occurrences<<" times"<<endl;
system("pause");
return 0;
}
我的目标是检查输入的数字在数组中显示了多少次然而,if的声明似乎给我带来了麻烦,有人能帮我吗?
看起来您正在访问数组的末尾:
if (inputnum == arrayofnum[i])
for循环允许i
在终止前取值10,因此在最后一次迭代中,您将访问arrayofnum[10]
。数组中的最后一个元素是arrayofnum[9]
。
请记住,c++中的数组是基于零的,所以您只需要像这样调整for循环:
for (int i = 0; i < 10; i++) {
/* stuff */
}
更改此
for(int i=1;i<=10;i++)
对此,
for(int i=0;i<10;i++)
看看是否有任何事情发生
根据cout'ed
和arrayofnum
的方式,我假设您确实知道数组的工作及其边界,即数组从index 0
开始,到maxCount-1
结束。所以,现在你必须看看你的for
循环,你就可以开始了。
for (int i = 0; i < 10; i++)
您的for循环不正确应该是for(int i=0;i<10;i++)
因为数组的大小是10,所以应该从0迭代到9。
我认为这可以很容易地完成。我会这样做:
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std ;
int main() {
int i , user_input , lim , mod , cn ;
lim = 10 ;
mod = 201 ;
cn = 0 ;
int arr[ lim ] ;
for( i = 0 ; i < lim ; i++ ) {
arr[ i ] = rand() % mod ;
}
cout << "Enter a number to check the occurencesn" ;
cin >> user_input ;
for( i = 0 ; i < lim ; i++ ) {
if( i != 0 ) {
cout << "," ;
}
cout << arr[ i ] ;
if( arr[ i ] == user_input ) {
cn++ ;
}
}
cout << "n" ;
cout << "The number of occurrences of " << user_input << " in the random list is " << cn << " times" << "n" ;
return 0 ;
}
此外,您正在访问数组中不存在的位置。数组的有效索引为[0,10]。
用替换for(int i=1;i<=10;i++)
for(int i=0;i<10;i++)
您的数组从索引0开始
相关文章:
- pyserial arduino 字节阵列解码问题
- 超级对撞机2D阵列:生成嵌套:包装/尺寸问题
- 阵列火稀疏矩阵问题
- 复制到新阵列时出现动态内存分配问题
- char,const char*阵列问题,用于mqtt client.publish
- 问题将信息复制到指针阵列中
- 问题创建和返回锯齿状阵列(错误std :: bad_array_new_length)
- 顶点阵列与类问题
- 自我创建级阵列[2]正在引起问题
- 气泡排序问题不会更改输入阵列
- C++动态阵列索引和容量问题
- 通过多维阵列迭代问题
- 相同大小的2D和1D阵列之间的内存或执行问题
- 阵列出现问题:/
- 存储到阵列的问题
- 在 2D 图像阵列中裁剪/插入 - 内存分配问题
- 阵列初始化问题
- C++阵列初始化的氧气问题
- 了解 DXGI DirectX 11 桌面复制以获取缓冲区或阵列的问题
- 阵列分配问题