Search code examples
c++intlong-long

Invalid operand of types 'long long int' to binary 'operator%'


i am in C++ and I get this error:

bool comprovarCodi(long long num, int DC){
bool codi_correcte;
int i=0, suma_senars=0, suma_parells=0, suma_total=0, desena_superior, DC_calculat, cont=0;
while(num!=0){
    num=num/10;
    cont++;
    i++;    
}
if(cont==12){
    for(int j=1; j<12; j=j+2){
        suma_senars=suma_senars+num%pow(10,j);

I don't know why, I believe "num" is an integer so I can use the operator "%".

Somebody knows why it fails?

Thank you


Solution

  • Don't use pow for this sort of thing.

    long long pow_ten = 10;
    for(int j=1; j<12; j=j+2)
    {
       suma_senars=suma_senars+num%pow_ten;
       pow_ten *= 100;
    }
    

    Not only will this be faster, it will also calculate correctly, rather than pow which may well use something like exp(log(x) * y) to calculate x ** y - and thus not always come up with precisely the number you wanted - particularly if you cast it back to integer.