Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        6年前关闭。
                                                                                            
                
        
到目前为止,这是我的代码

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

10-05 18:27
查看更多