Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

c - Variable Buffer?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...