+ 2
What is wrong with my code(what should be there for negative exponents)[N.B.:you can't use power function.]
#include<stdio.h> #include<math.h> int main() { int x,n; float power=1,inv=1; inv = 1 / x; printf("x="); scanf("%d",&x); printf("n="); scanf("%d",&n); int i=0; if(n>=0) { while(i<n) { power*=x; i++; } printf("%d^%d=%.4f",x,n,power); } else { n=-n; while(i<n) { power=power*inv; i++; } printf("%d^%d=%.4f",x,n,power); } return 0; }
1 Antwort
+ 5
Your most obvious problem is using x prior to reading it. You assign 1/x to inv and 2 lines later scanf into x. The value x has could be anything as it will use whatever was left in it's memory location. The only thing guarenteed is inv will almost never have the value you thought.