Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have this code which calculates the exponential power of a value, both of which is entered by the user, example, user enters 2^3 = 8, its suppose to work like this but somethings wrong, the end result is 608, when I debug in the pwra function in the counter, even before the counter initiates the result value is set, from where I dont know because I did not set it so the end result is 608. I feel like its a buffer issue but I have tried fflush both in and out, it doesnt work. So when I copy this code to a new window, it works for sometime, then same again, earlier it was showing 624 as the end result.

#include <stdio.h>
int pwra (int, int);

int main()
{
   int number, power, xx;
   printf("Enter Number: ");
   scanf("%i", &number);

   printf("Enter Number: ");
   scanf("%i", &power);

   xx=pwra (number,power);
   printf("Result: %i", xx);

   return 0;
}

int pwra (int num, int pwr)
{
   int count, result;

   for(count=1;count<=pwr;count++)
   {
      result = result*num;
   }
   return result;
}

Another thing, how can I calculate the exponential value from a float, because when I change all the int to float the end result is always 0.00000 even with %lf.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
253 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're hitting undefined behavior for the below line

 result = result*num;

as you've not initialized result. The initial value for an uninitialized automatic local variable is indeterminate. Using that invokes UB.

Always initialize your local variables, like

 int count = 0 , result = 0 ; //0 is for illustration, use any value, but do use

Then coming to the case, where you want to change all ints to float, only changing the data type of the variable is not sufficient. You need to change the corresponding format specifiers, too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...