2

After compiling the following program I get the output "2346" but was expecting "2345".

#include<math.h>
#include<iostream.h>
int nr_cif(int a)
{
    int k=0;
    while(a!=0)
    {
        a = a/10;
        k++;
    }
    return k;
}

void Nr(int &a){
    int k = nr_cif(a);
    a = a % (int)pow(10,k-1);
}


int main()
{
    int a = 12345;
    Nr(a);
    cout<<a;
}

After debugging I noticed that it bugs out after it evaluates: a = a % (int)pow(10,k-1). Why does it break here?

  • 2
    Use ``, not ``. `` would be a bit better as `` as well. – chris Mar 29 '14 at 22:24
  • Does this answer your question? [Why does pow(5,2) become 24?](https://stackoverflow.com/questions/22264236/why-does-pow5-2-become-24) – phuclv Jun 07 '21 at 09:18
  • [Why pow(10,5) = 9,999 in C++](https://stackoverflow.com/q/9704195/995714), [Why does gcc compiler output pow(10,2) as 99 not 100?](https://stackoverflow.com/q/25474351/995714), [Why does pow(5,2) become 24?](https://stackoverflow.com/q/22264236/995714) – phuclv Jun 07 '21 at 09:19

2 Answers2

1

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.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • Thanks for the comment but I don't think it works as it should with this code. For example if we take a = 12. It will go twice through the while loop therefore ten_k will end up being 100. Then 'a' won't change its value. I want it to remove its first digit – user3461699 Mar 29 '14 at 22:35
  • @user3461699: Ok, you're right. Use `a % (ten_k/10)` – Ben Voigt Mar 29 '14 at 22:53
0

I'm not amazing or great at math but this seems to work: http://ideone.com/dFsODB

#include <iostream>
#include <cmath>

float mypow(float value, int pow)
{
    float temp = value;
    for (int i = 0; i < pow - 1; ++i)
        temp *= value;

    for (int i = 0; i > pow - 1; --i)
        temp /= value;

    return temp;
}


int main() 
{
    std::cout<<pow(10, -3)<<"\n";
    std::cout<<mypow(10, -3)<<"\n";
    return 0;
}
Brandon
  • 22,723
  • 11
  • 93
  • 186