After compiling the following program I get the output \"2346\" but was expecting \"2345\".
#include
#include
int nr_cif(int a)
{
It's not a very good idea to use pow
for integer math. I would change the code as follows:
void Nr(int &a)
{
int ten_k = 1;
while (ten_k < a) ten_k *= 10;
a %= ten_k/10; // 10-to-the-(k-1)
}
There's nothing in your code that needs the number of decimal digits, only the place value. So make the place value your variable.
(You could also use your original while loop, which works better for negative inputs. But calculate and return 10-to-the-k-power, instead of k).
The problem with pow
is that it works with floating-point values, and gives results that are very close but not exact. The error might be just enough to cause the rounded value (after cast to int
) to be wrong. You can work around that by adding 0.5 before casting... but there's no point, since multiplying in your loop is faster than calling pow
anyway.