-1

I tried to loop thru an array pointer to get the even numbers in that array.

void even_element(double* a, const int SIZE)
{
for (int count = 0; count < SIZE; count ++)
{
    if(a[count] % 2 == 0) //Error here
    {
        cout << *(a + count) << " ";
    }
}
}

I know if I do in the main method where the array is declared, I can do this without using pointer :

for (int count = 0; count < SIZE; count ++)
{
    if(num_array[count] % 2 == 0)
    {
        cout << num_array[count] << " ";
    }
}

However, when I try to do this with pointer, I do not know how to loop thru the elements in an array. Can somebody please guide me?

Thanks in advance.

Elazar
  • 20,415
  • 4
  • 46
  • 67
  • 2
    What error are you getting? You have more information about the problem than we do. – Peter Wood May 29 '13 at 08:42
  • Expression must have integral or enum type –  May 29 '13 at 08:42
  • Are you sure the error isn't in this line `cout << *(a + count) << " ";`? – Steve May 29 '13 at 08:42
  • Nope. it's at the if statement there –  May 29 '13 at 08:44
  • The code in your second example is absolutly equivalent to the first one. you don't need an array - a pointer will suffice. – Elazar May 29 '13 at 08:46
  • I know how to do without pointer and that's why I am showing. I do not want anyone say that I am just simply asking for solution without putting effort. However, I want to gain knowledge on pointer but I am stuck. –  May 29 '13 at 08:48
  • Your problem has nothing to do with pointers but with simple arithmetics. – Elazar May 29 '13 at 08:50
  • 1
    The expression doesn't have an integral or enum type. You can't take the modulus of a `double`. – Peter Wood May 29 '13 at 08:50
  • Okay thanks peter wood. I fixed it already –  May 29 '13 at 08:51
  • I think some (not all) people, including myself starting off thinking the code was compiling and you were getting unexpected results. It would have been more helpful if you could have explained that the error was a compile time error and the error message in the question itself. – Steve May 29 '13 at 08:55

2 Answers2

4

When working with floating point numbers, you should use fmod instead of the integer modulo operator %.

However, be careful when dealing with floating point values: you cannot directly compare values. You have to compare the absolute difference between the value and a very small, epsilon value.

Matthieu Rouget
  • 3,289
  • 18
  • 23
  • You _can_ compare `fmod(a[count], 2) == 0.0`. However, depending on what you want to calculate, you man want to know which of you doubles are _nearly even_, because equality is hard to achieve with doubles. You can use then `fmod(a[count], 2) < epsillon` where `epsillon` is a very small double. – Matthieu Rouget May 29 '13 at 09:06
1

you can't use '%' with double. following link is useful for you:

Can't use modulus on doubles?

Community
  • 1
  • 1
rishikesh tadaka
  • 483
  • 1
  • 6
  • 18