whether the number is even or odd in a single array

Asked

Viewed 110 times

-1

  float vet[10];
//processamento
for(x=0;x<=9;x++)
{
    printf("\n informe o %d° número:",x+1);
    scanf("%f",&vet[x]);
//saída de dados
    if (vet[x] % 2 == 0)
    {
        printf("\n O número %2.f é par",vet[x]);
    }
    else
    {
        printf("\n O número %2.f é impar",vet[x]);

how can I know if the value I enter will be odd or even

  • when I run it it appears here: error: invalid operands to Binary % (have 'float' and 'int')

  • The concept of even/odd is applicable to integers as well as the operator % (rest of the division) which is set to integers. For real values there is the function fmod of <Math. h>.

1 answer

0

The code is returning this error because the operator % only works with numbers inteiros, and its vector has a type float.

Just use typecasting, which is to place the new data type in parentheses before the variable. However, by doing this, you do not change the type of variable, you just convert the data.

If you want to save the converted value, you must declare another variable. In your case, this is not necessary, because you just check whether the condition is true or not, and then discard the obtained value.

Put the (int) before the variable to convert it:

  if ((int)vet[x] % 2 == 0)
  {
     printf("\n O número %1.f é par",vet[x]);
  }
  else
  {
     printf("\n O número %1.f é impar",vet[x]);
  }

Realize that the %2.f need to be replaced by %1.f, not to display decimal places, but cannot be replaced by %d, because the value of vet[x] is still a float.

I noticed that in this code snippet you did not declare the variable x that he used in the for, don’t forget to do it later.

Source: https://www.tutorialspoint.com/cprogramming/c_type_casting.htm

Browser other questions tagged

You are not signed in. Login or sign up in order to post.