每当我运行它时,它最终会给我数组中的对象数量。我是整个指针的新手,无法弄清楚我做错了什么。我需要它来显示给定数组中偶数的数量,而不是数组中所有数字的数量。谢谢!!! :)
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;
}
答案 0 :(得分:0)
if (a[b]%2==0);
在此处删除分号:您希望以下块依赖于条件的结果,但分号在此处结束语句。
cout << endl << "The total amount of even numbers is " << c << endl;
我觉得你的意思是e
,而不是c
。您希望显示前一行中返回的值counteven
,而不是总数。
通过这两项更改,您的样本可以正常运行。