1

I am trying to implement the below formula on C

enter image description here

Here is my code:

int function(int x){
   return pow(10, (((x-1)/(253/3))-1));
}

int main(void){
  int z = function(252);
  printf("z: %d\n",z); 
  return 0;
}

it outputs 10. However a calculator outputs 94.6.

could anyone explain me what I am doing wrong?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Johan Elmander
  • 646
  • 2
  • 8
  • 11
  • 2
    (((252-1)/(253/3))-1) == ((251/84)-1) == (2-1) == 1. 10^1 == 10. Good old integer division. – Mike Jul 11 '13 at 18:36
  • 4
    Why the downvote? The question was pretty straightforward. – gifnoc-gkp Jul 11 '13 at 18:36
  • @TheOtherGuy "questions must demonstrate a minimal understanding of the problem being solved". And they "must show some research effort" too. Any reasonably good beginner C language guide mentions integer division. –  Jul 11 '13 at 18:37
  • 1
    @TheOtherGuy Also: upvotes are not for "correcting" downvotes. –  Jul 11 '13 at 18:38
  • 4
    @H2CO3 I'd rather believe that he simply didn't notice it. We're not robots. – gifnoc-gkp Jul 11 '13 at 18:39
  • @TheOtherGuy Possible. –  Jul 11 '13 at 18:39
  • 3
    @TheOtherGuy - while sometimes I find H2CO3 to be.. somewhat harsh, in this case I agree with him. We may not be robots, but we are capable of using debuggers and breaking down problems. Expanding the code of `function()` the way I did in the comments and following along with a calculator would have shown that when dividing `int`s the values were not as expected; that would then lead to the answer that `int` division is to blame – Mike Jul 11 '13 at 18:43
  • It's a total stretch that this question is a duplicate. Don't get me wrong, I still think it should be closed for showing lack of effort, but so does the duplicate question. –  Jul 12 '13 at 05:15

2 Answers2

7

Note that in this line

(((x-1)/(253/3))-1))

You are dividing the integer value x - 1 by an integer value 253 / 3. This will truncate the value to an int, meaning that you'll be raising an integer power to an integer power.

To fix this, try changing this expression to

(((x-1)/(253.0 / 3.0))-1))

This now will use doubles in the expression, giving you the value you want.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

Adding to that, integers do not give you the decimal part of numbers, so a number like 3.5 will get cut down to 3 using integer. To fix this double is the way to go. In other words 3 is different than 3.0

StevenTsooo
  • 498
  • 4
  • 13