0
Good night. I’m making a program that converts numerical bases into Qt Creator using C++, and the function that converts from any base to decimal, has a loop for:
int toDeci(QString str, int base)
{
int len = str.size();
int num = 0; // Initialize result
int valor;
int i = 0;
int potencia;
for (i = 0; i < len; i++)
{
qDebug() << "Valor de i no inicio: " << i;
if (val(str.at(i)) >= base)
{
return -1;
}
else
{
qDebug() << "Inicio do loop";
qDebug() << "Valor de i: " << i;
valor = val(str.at(i));
qDebug() << "Valor do caractere: " << valor;
qDebug() << "Valor de len " << len;
potencia = qPow(base, len-1);
qDebug() << "Valor da potencia: " << potencia;
num += val(str.at(i)) * qPow(base, len-1);
qDebug() << "Valor de num: " << num;
len--;
qDebug() << "Fim do loop";
qDebug() << "Valor de i no inicio: " << i;
}
}
return num;
}
The problem is that the loop is running twice. I put these qDebug() to show the values of the variables, and it seems that the control variable i is restarted once, making the loop run twice, even with Len worth 1. In debug comes that:
Valor de i no inicio: 0
Inicio do loop
Valor de i: 0
Valor do caractere: 1
Valor de len 1
Valor da potencia: 1
Valor de num: 1
Fim do loop
Valor de i no final: 1
Valor de i no inicio: 0
Inicio do loop
Valor de i: 0
Valor do caractere: 1
Valor de len 1
Valor da potencia: 1
Valor de num: 1
Fim do loop
Valor de i no final: 1
How to make the loop run only once? Changing the initial value of i makes the loop not run.