Remainder operator (%) is unable to use doubles and int as operands even though documentation says it can

This is the code I've written.

const int ledPin[] = {4,5,6,7};

long int numAleat; // Escolhe um número de 32 bits aleatório
int comprimento;
int i;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  for (int i=0;i<4;i++){
  pinMode(ledPin[i], OUTPUT);
  }
}
void loop() {
  // put your main code here, to run repeatedly:


  numAleat=48367;
  String stg_numAleat;
  stg_numAleat = String(numAleat);
  int comprimento = stg_numAleat.length();
  unsigned primeiro = (numAleat%10);
  unsigned segundo = (numAleat /10U) %10;
  unsigned terceiro = (numAleat /100U) %10;
  unsigned quarto = (numAleat /1000U) %10;

  for(i=0;i< 10*comprimento +1;i= i +10){ 
    if (i==0){
      Serial.println(numAleat%10);
     }
   else{ 
     for(int a=0; a=comprimento;a++){
    Serial.println((numAleat/ pow(10,a) ) %10);
    }
    }
    delay(1000);  }
delay(9999);  
Serial.println(quarto);

  delay(99999);
  }

The specific error is in this line

    Serial.println((numAleat/ pow(10,a) ) %10);

It spews this error

Compilation error: invalid operands of types 'double' and 'int' to binary 'operator%'

I've tried converting it to int

    Serial.println(int(numAleat/ pow(10,a) ) %10);

But then it just spams the Serial Monitor with a bunch of 0s.
How to fix this?

Maybe a<=comprimento ?

1 Like

Do you want an integer or a float? The modulo operator ( % ) does not work with floats, you will need to cast the result of the division to an integer type before using modulo, or you can use fmod() for a floating point answer.

1 Like

Lol, thanks. I've missed that completely

why not

   long pwr = 1;
   for(int a=0; a=comprimento; a++) {
    Serial.println( (numAleat/pwr) %10);
    pwr *= 10;
   }

and abandon floating point use entirely.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.