使用for循环计算x到y的幂

问题描述 投票:0回答:2

我尝试使用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();

}
c for-loop long-integer
2个回答
1
投票

在为z分配值之前,您正在将x分配给xz然后有一个不确定的值,这会使功率的计算混乱。

您必须等待直到从用户输入分配了x才能使用其值初始化z

此外,从scanf读取输入时,最佳做法是检查其返回值以确保成功读取所有预期值:

if(scanf("%d %d", &x, &y) != 2)
{
    // x and y were not properly read - handle error
}

z = x;

1
投票

您正在初始化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”中,代码​​将在您放置它的位置执行,并且没有“引用变量”之类的东西。


0
投票

首先您可能要初始化这些变量

© www.soinside.com 2019 - 2024. All rights reserved.