0

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

2 Answers2

1

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.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
0

you have to cast to int first
suma_senars = suma_senars + num % (int)pow(10,j);
better: suma_senars += num % (int)pow(10,j);
clearer: suma_senars += num % ( (int)pow(10,j) );

I3ck
  • 433
  • 3
  • 10
  • Actually, I think your clearer line is less clear than your better line -- extra redundant parenthesis generally make things harder to read IMO. – Chris Dodd Dec 30 '15 at 20:53
  • 2
    It is a bad idea, since you can easily get unexpected result due to cutting of the floating part. `(int)9.9999` is `9`, not `10`. In general, as **@Mats** said, do not use `pow` in such scenarios. – AlexD Dec 30 '15 at 20:58