简体   繁体   English

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

[英]calculating x to power y using for loop

I've tried to use the for loop for calculating x to power y.我尝试使用for循环来计算 x 为 y 提供动力。 The program is running but giving errors.程序正在运行但出现错误。

To my knowledge, the error must be in "z" statements but I cannot figure it out.据我所知,错误必须在“z”语句中,但我无法弄清楚。 Help me if you encounter my mistakes.如果您遇到我的错误,请帮助我。

#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();

}

You are assigning z to x before x is assigned a value.您正在分配zx之前, x被分配一个值。 z then has an indeterminate value, which messes up calculation of the power. z然后有一个不确定的值,这会扰乱幂的计算。

You have to wait until x is assigned from user input before using its value to initialize z .在使用x的值初始化z之前,您必须等到x从用户输入中分配。

Also, when reading input from scanf , it's a best practice to check its return value to ensure that all intended values were read successfully:此外,从scanf读取输入时,最佳做法是检查其返回值以确保成功读取所有预期值:

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

z = x;

EDIT: @chux - Reinstate Monica pointed out in the comments that if y == 0 the code still has a problem.编辑:@chux - 恢复莫妮卡在评论中指出,如果y == 0代码仍然有问题。 Anything to the power of zero (except zero itself, since x y is not continuous at the origin) is 1. You have to handle that special case as well.任何的零次方(除了零本身,因为 x y在原点不连续)都是 1。你也必须处理这种特殊情况。

You are initializing your z variable (to be equal to x ) before you have assigned a value to x !要初始化您的z变量(等于x )已设定值x To fix this, move the declaration/initialization of z to after your scanf call:为了解决这个问题,移动的声明/初始化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"
    //..

EDIT: Maybe I'm drifting a bit 'off-topic' here, but you may have a background in programming languages that use reference variables (C++ or C#)?编辑:也许我在这里有点“题外”,但您可能有使用引用变量(C++ 或 C#)的编程语言的背景? In such languages, what you are trying to do may work!在这些语言中,您尝试做的事情可能会奏效! For example, in C++, you could have int& z = x;例如,在 C++ 中,您可以使用int& z = x; (where you have your current declaration), and that could work in some circumstances (although, in your code, it actually won't, as pointed out in the comments). (您有当前声明的地方),并且在某些情况下可以工作(尽管在您的代码中,它实际上不会,正如评论中指出的那样)。 However, in "plain old C," code is executed where you put it, and there's no such thing as a "reference variable."但是,在“普通的旧 C”中,代码​​在您放置的地方执行,并且没有“引用变量”这样的东西。

First you might want to initialize those variables首先你可能想初始化这些变量

long int x = 0, y = 0;
long int z = 0;

Here you should check if scanf was successful在这里你应该检查scanf是否成功

printf("Enter the values of x and y: ");
scanf("%ld %ld",&x,&y);

About scanf return value.关于scanf返回值。 From cppreference来自cppreference

Return value 1-3) Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.返回值 1-3) 成功分配的接收参数的数量(如果在分配第一个接收参数之前发生匹配失败,则可能为零),如果在分配第一个接收参数之前发生输入失败,则为 EOF。 4-6) Same as (1-3), except that EOF is also returned if there is a runtime constraint violation. 4-6) 与 (1-3) 相同,除了如果存在运行时约束违规也会返回 EOF。

Now the problem is you're assigning z the value of x before either is initialized properly.现在的问题是,你要指定zx之前,无论是正确初始化。 So that is an undefined behavior.所以这是一个未定义的行为。

This is what you want这就是你想要的

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;

Also you can define a new int variable inside the loop.您也可以在循环内定义一个新的int变量。 I personally find this method better.我个人觉得这个方法更好。

for(int i = 2; i <= y; i++) 
    z *= x;

For the print statement, you might want to use %ld format for long int对于print语句,您可能希望对long int使用%ld格式

printf("%ld to power %ld is %ld",x,y,z);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM