0

I am trying to write a program that gives output if the input is an integer (say 1234)

1234
234
34
4

I wrote the following code in C using codeblocks IDE :

#include <stdio.h>
#include <math.h>
int main()
{
 int a,l=0,b;
 print("Enter a number : ");
 scanf("%d",&a);
 b =a;
 while (b>0)
 {
    l++;
    b = b/10;
 }
 l=l-1;
 while(a>0)
 {
    printf("%d\n",a);
    b = (int)pow(10,l);
    printf("10^%d = %d\n",l,b ); //Testing statement

    a = a % b;
    l--;
}

return 0;
}

Initially, I was puzzled seeing the output but to test I wrote the test statement to see what is happening.

I don't think there is some problem with the logic. Because when I put a=1234 and run this I get the following output : image

Initially, I thought the problem is due to the pow function which is a double type, so I cast it into int type. Can someone explain what is the error here? I can write my own pow function which returns an int but I want to know why this pow function behaving like this?

Infinity_hunter
  • 157
  • 1
  • 7
  • 1
    `(int)` always rounds a positive number down. So if `pow(10,2)` returns `99.999999`, you get `99` instead of `100`. – Barmar Sep 17 '21 at 16:13
  • Use **integer** power: `int ipow(int base, unsigned exp) { int val = 1; while (exp--) val *= base; return val; }` – pmg Sep 17 '21 at 16:14
  • The fundamental problem here is that `pow()` is doing everything with logarithms or the equivalent, so that it can do things like `pow(2, 0.5)`. Some implementations recognize when the second argument is an integer, to guarantee a more accurate result, with no funny roundoff errors. Looks like your implementation doesn't. – Steve Summit Sep 17 '21 at 16:17
  • 1
    @pmg I love to use [binary exponentiation](https://en.wikipedia.org/wiki/Exponentiation_by_squaring) in that case. – Steve Summit Sep 17 '21 at 16:18
  • @Steve Summit Indeed. I just checked the same code in an online compiler that gave the correct output. – Infinity_hunter Sep 17 '21 at 16:19
  • @pmg or maybe something like this https://gist.github.com/orlp/3551590 – Aykhan Hagverdili Sep 17 '21 at 16:21
  • `pow` does floating-point math so the result might not be exact for integer math: [Why does pow(5,2) become 24?](https://stackoverflow.com/q/22264236/995714), [Why pow(10,5) = 9,999](https://stackoverflow.com/q/9704195/995714) – phuclv Sep 17 '21 at 16:34

0 Answers0