【问题标题】:Can't figure out how to return the proper amount of even numbers in the array无法弄清楚如何在数组中返回适当数量的偶数
【发布时间】:2014-01-27 08:07:14
【问题描述】:

每当我运行它时,它最终都会给我数组中的对象数量。我是整个指针的新手,无法弄清楚我做错了什么。我需要它来显示给定数组中偶数的数量,而不是数组中所有数字的数量。谢谢!!! :)

 int counteven(int *a, int size)
//reserves space for the pointer of a certain size
{   int b;
int c=0;
for (b=0; b<size; b++)
{
    if (a[b]%2==0); 
    //if the remainder is 0 when dividing by 2 add
    //1 to the amount of even numbers
    {
        c++;
    }
}
return c;
}
int main () 
try {

int *a, b=0, c, e;
cout << "\n Please enter how many numbers you have: ";
//displays instructions
scanf("%d", &c);
a=(int *)malloc(c * sizeof(int));
//allocates a block the size of the int
for(b=0; b<c; b++)
    {
        printf( "Please enter a[%d]: " , b+1);
        //prompts the user to enter the first, second, third and
        //so on number that they want to determine whether or not
        //is even
        scanf("%d", (a+b));
    }
    for (b=0;b<c;b++)
    {
        printf("a[%d]=%d \n", b+1, *(a+b));
    }
    e=counteven(a,c);
    cout << endl << "The total amount of even numbers is " << c << endl;
    return 0;

}
catch (...) {
cout << "Exception occurred" << endl;
}

【问题讨论】:

    标签: arrays pointers


    【解决方案1】:

    if (a[b]%2==0);

    在此处删除分号:您希望以下块依赖于条件的结果,但分号在此处结束语句。

    cout &lt;&lt; endl &lt;&lt; "The total amount of even numbers is " &lt;&lt; c &lt;&lt; endl;

    我认为您的意思是e,而不是c。您希望显示上一行返回的值counteven,而不是总数。

    通过这两项更改,您的示例可以正常工作。

    【讨论】:

    • 啊啊谢谢!!!这么小的事情会导致编码中的这么大的错误哈哈谢谢:)
    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    相关资源
    最近更新 更多