Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Trouble with powers in C?

Trying to find the 2^5 and 2^-5 using C. This is what I've got but the output for 2^-5 is coming up as 0.00000 and I'm not sure why. I can't use any math libraries, so that's out.

int main(void)

{

int x, n, k;

int answerpositive;

float answernegative;

x=2;

n=5;

answerpositive = 1;

for (k=0; k<n; k++)

{

answerpositive = answerpositive*x;

}

printf("%d ", answerpositive);

answernegative = 1/answerpositive;

printf("%f", answernegative);

return EXIT_SUCCESS;

}

2 Answers

Relevance
  • 9 years ago
    Favorite Answer

    Change

    answernegative = 1 / answerpositive;

    to

    answernegative = 1.0 / answerpositive;

    or

    answernegative = 1 / (float)answerpositive;

    Your original division has ints on both sides, to integer division takes place before being implicitly cast to a float. If you change one side of the division to a float (e.g. by using 1.0 rather than 1) then floating point division will occur and all will be well!

  • 9 years ago

    answerpositive is declared as integer.

    So any division as

    1/answerpositive;

    is going to be zero. An integer divide. Instead, declare your answers as float or double. Do not use one for positive and another for negative.

Still have questions? Get your answers by asking now.