[英]calculating x to power y using for loop
我尝试使用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
之前,您必须等到x
从用户输入中分配。
此外,从scanf
读取输入时,最佳做法是检查其返回值以确保成功读取所有预期值:
if(scanf("%d %d", &x, &y) != 2)
{
// x and y were not properly read - handle error
}
z = x;
编辑:@chux - 恢复莫妮卡在评论中指出,如果y == 0
代码仍然有问题。 任何的零次方(除了零本身,因为 x y在原点不连续)都是 1。你也必须处理这种特殊情况。
要初始化您的z
变量(等于x
)已设定值前x
! 为了解决这个问题,移动的声明/初始化z
你以后scanf
调用:
//..
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"
//..
编辑:也许我在这里有点“题外”,但您可能有使用引用变量(C++ 或 C#)的编程语言的背景? 在这些语言中,您尝试做的事情可能会奏效! 例如,在 C++ 中,您可以使用int& z = x;
(您有当前声明的地方),并且在某些情况下可以工作(尽管在您的代码中,它实际上不会,正如评论中指出的那样)。 但是,在“普通的旧 C”中,代码在您放置的地方执行,并且没有“引用变量”这样的东西。
首先你可能想初始化这些变量
long int x = 0, y = 0;
long int z = 0;
在这里你应该检查scanf
是否成功
printf("Enter the values of x and y: ");
scanf("%ld %ld",&x,&y);
关于scanf
返回值。 来自cppreference
返回值 1-3) 成功分配的接收参数的数量(如果在分配第一个接收参数之前发生匹配失败,则可能为零),如果在分配第一个接收参数之前发生输入失败,则为 EOF。 4-6) 与 (1-3) 相同,除了如果存在运行时约束违规也会返回 EOF。
现在的问题是,你要指定z
值x
之前,无论是正确初始化。 所以这是一个未定义的行为。
这就是你想要的
long int x = 0, y = 0;
long int z = 0;
printf("Enter the values of x and y: ");
scanf("%ld %ld",&x,&y);
z = x;
您也可以在循环内定义一个新的int
变量。 我个人觉得这个方法更好。
for(int i = 2; i <= y; i++)
z *= x;
对于print
语句,您可能希望对long int
使用%ld
格式
printf("%ld to power %ld is %ld",x,y,z);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.