我一直在研究一些基本的编码,我正在努力找出正确的扫描方式,第一个是我的x变量,第二个是x被提升到的n.我尝试5 ^ 5并使用我当前的代码获得-287648.
#include <stdio.h>
#include <math.h>
void x_to_the_n (void)
{
int x=0;
int n =0;
long int y;
printf("Enter a integer for X and N\n");
scanf("%i\n%i\n",&x,&n);
y=pow(x,y);
printf("%i \n",y);
}
int main(void)
{
x_to_the_n ();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我很确定你的意思是:
y = pow(x, n);
~~
Run Code Online (Sandbox Code Playgroud)
你得到了一个"怪异"的结果,因为y它永远不会被初始化为任何东西; 你正在提高x(一些垃圾)和垃圾的力量.
请注意,正如@ 0A0D在评论中建议的那样,如果您要使用更多描述性变量,则此问题会更加明显:
int base = 0;
int exponent = 0;
long int result;
printf("Enter the base and exponent, on separate lines\n");
scanf("%i\n%i\n", &base, &exponent);
result = pow(base, result);
~~~~~~~ oops!
Run Code Online (Sandbox Code Playgroud)
另外,正如@icepack所提到的,因为y是a long int,格式应该是%li(不是%i):
printf("%li\n", y);
Run Code Online (Sandbox Code Playgroud)