我尝试使用for
循环来计算x乘以y。该程序正在运行,但出现错误。
据我所知,该错误必须在“ z”语句中,但我无法弄清楚。如果您遇到我的错误,请帮助我。
#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,i;
long int z=x;
printf("Enter the values of x and y: ");
scanf("%d %d",&x,&y);
for(i=2;i<=y;i++)
z*=x; ```
/*e.g- Let x=2, y=3, then as per intialization z=x=2
since,from the for condition, (i=2)<=3, which is true
z= z*x =>2*2 => 4 now z=4
now i++ => i=3
(i=3)<=3,which is true
z= z*x =>4*2 => 8
therefore, 2 to power 3 is 8 */
printf("%d to power %d is %ld",x,y,z);
getch();
}
在为z
分配值之前,您正在将x
分配给x
。 z
然后有一个不确定的值,这会使功率的计算混乱。
您必须等待直到从用户输入分配了x
才能使用其值初始化z
。
此外,从scanf
读取输入时,最佳做法是检查其返回值以确保成功读取所有预期值:
if(scanf("%d %d", &x, &y) != 2)
{
// x and y were not properly read - handle error
}
z = x;
您正在初始化z
变量(等于x
)之前,您已经为x
分配了一个值!要解决此问题,请将z
的声明/初始化移至scanf
调用的after:
//..
int x,y,i;
// long int z=x; // Means nothing: as "x" is here undefined, so "z" will also be!
printf("Enter the values of x and y: ");
scanf("%d %d",&x,&y);
long int z = x; // Here, we have (probably) a value for "x" so we can copy it to "z"
//..
编辑:也许我在这里有点偏离主题,但您可能在使用reference变量(C ++或C#)的编程语言中有背景知识?在这种语言中,您trying所要做的可能有效!例如,在C ++中,您可以使用int& z = x;
(其中有当前的声明),并且可以使用。但是,在“普通旧C”中,代码将在您放置它的位置执行,并且没有“引用变量”之类的东西。
首先您可能要初始化这些变量