0

我在 C++ 中,我收到此错误:

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);

我不知道为什么,我相信“num”是一个整数,所以我可以使用运算符“%”。

有人知道为什么会失败吗?

谢谢

4

2 回答 2

1

不要pow用于这种事情。

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

这不仅会更快,而且会正确计算,而不是pow使用类似exp(log(x) * y)计算的东西x ** y- 因此并不总是准确地得出你想要的数字 - 特别是如果你将它转换回整数。

于 2015-12-30T20:56:25.980 回答
0

你必须先
suma_senars = suma_senars + num % (int)pow(10,j);
更好地转换为 int: suma_senars += num % (int)pow(10,j);
更清晰: suma_senars += num % ( (int)pow(10,j) );

于 2015-12-30T20:48:22.433 回答