C++
#include <math.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
int cubo = 0;
cubo = pow(5, 3);
cout << "POW a traves de la variable 'cubo': " << cubo << endl; // me devuelve 124 (mal)
cout << "POW directamente a consola: " << pow(5, 3); // me devuelve 125 (bien)
return 0;
}
I have only detected it, for the moment, with 5, both squared and cubed. In the first case, squared, it returns 24 per variable (bad), and 25 directly to the console (good)
I have continued messing around with this "problem", and I have devised a code to detect which number raised to which power gives a different result, if it is passed through a variable or if it goes directly to the console.
I explain myself after the code:
C++
#include <math.h>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
int resultado_variable = 0;
int cantidad = 0;
float potencia = 0;
cout << "\nEscribe la cantidad de numeros a elevar a partir del 1: ";
cin >> cantidad;
cout << "Escribe la potencia a elevar: ";
cin >> potencia;
for (int i = 1; i <= cantidad; i++)
{
resultado_variable = pow(i, potencia);
if (resultado_variable != pow(i, potencia))
{
cout << "\n" << i << "^" << potencia << endl;
cout << "POW a traves de la variable: " << resultado_variable << endl;
cout << "POW directamente a consola: " << pow(i, potencia) << endl;
}
}
cout << "\n";
return 0;
}
Whether the variable or the iterator of the FOR loop are declared as as
float
far as I have tested, the code does not detect differences, which would be a satisfactory solution to avoid this phenomenon, and perform a calculation of some precision.
But if the variable or the iterator is declared as an integerint
, that is when some very curious results appear. That is, the same numbers on the screen that the code detects as different.
In fact, I don't like the rounding, since it seems that when faced with a result like 24.99999999..., which would still be 25 when rounded, C++ doesn't take decimals into account and keeps the integer, in this case 24 Logical thing
, I think, when declaring the variable asint
.
But I don't quite understand why that affects the loop iterator.