c++ - 数组 :/有问题

标签 c++ arrays for-loop

<分区>

到目前为止,这是我的代码

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 */
}

关于c++ - 数组 :/有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20344470/

相关文章:

c++ - 内存对齐、结构和 malloc

c++ - 对象的 ctor 和 dtor 必须在同一个线程上吗?

javascript - for循环中的jquery迭代器

Python - 如何在检查前向元素时循环遍历列表?

c++ - 这个线程池/多核模拟有什么问题

c++ - boost::asio::yield_context 可以设置 std::error_code 而不是 boost::system::error_code 吗?

java - 如何动态地在整数数组中添加元素?

python - 忽略指定值的 numpy 数组的平均值

arrays - 如何使用加入?

c - 使用 switch - C 后简单程序崩溃