阵列出现问题:/

Having trouble with Arrays :/

本文关键字:问题 阵列      更新时间:2023-10-16

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

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'edarrayofnum的方式,我假设您确实知道数组的工作及其边界,即数组从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开始