简体   繁体   English

为什么for循环在c中无限进行

[英]why is the for loop going on infinitely in c

my question is when I run the code the loop goes on infinitely.我的问题是当我运行代码时,循环会无限进行。 the expected output is to print hi 5 times then go to a new line and print 4 times the 3 and so on I cant understand what is causing the loop to go infinite.预期的 output 是打印 hi 5 次,然后将 go 打印到新行并打印 4 次 3 等等我无法理解是什么导致循环到 Z34D1F91FB2E514B8576FAB1A7BZA8 无限。

#include <stdio.h>
int star(int);
int main()
{
    printf("enter number\n");
    int a;
    scanf("%d", &a);
    star(a);
    return 0;
}

int star(int m)
{

    int n;
    for (n = 0; n < m; n++)
    {
        printf("hi");
    }
    printf("\n");

    star(m - 1);

    return 0;
}

you forgot to check if m > 0 somewhere in your function.您忘记检查 function 中某处是否 m > 0。 In this case, the loop goes infinetely, because it doesn´t have a way to get out of recursion.在这种情况下,循环无限循环,因为它没有办法摆脱递归。

Simple fix:简单修复:

#include <stdio.h>
int star(int);
int main()
{
    printf("enter number\n");
    int a;
    scanf("%d", &a);
    star(a);
    return 0;
}

int star(int m)
{

    int n;
    for (n = 0; n < m; n++)
    {
        printf("hi");
    }
    printf("\n");
    if (m > 0){
        star(m - 1);
    }
    return 0;
}

For starters the return type of the function star is useless and does not make a sense.对于初学者来说,function star的返回类型是无用的,没有任何意义。 Also there is no great sense to declare the parameter as having the signed integer type int .此外,将参数声明为具有签名的 integer 类型int也没有太大意义。 It would be more logically correct to declare the parameter as having at least the unsigned integer type unsigned int .将参数声明为至少具有无符号 integer 类型unsigned int在逻辑上更正确。

So the function should be declared like所以 function 应该声明为

void star( unsigned int n );

The function calls infinitely itself recursively because such a call is unconditional and does not depend on the value of the parameter m . function 无限递归地调用自身,因为这样的调用是无条件的并且不依赖于参数m的值。

int star(int m)
{
    //...
    star(m - 1);
   
    return 0;
}

The function can be defined the following way as it is shown in the demonstrative program below. function 可以通过以下方式定义,如下面的演示程序所示。

#include <stdio.h>

void star( unsigned int );

int main( void )
{
    printf( "Enter number: " );
    unsigned int n;

    if ( scanf( "%u", &n) == 1 ) star( n );

    return 0;
}

void star( unsigned int n )
{
    if ( n )
    {
        for ( unsigned int i = 0; i < n; i++)
        {
            printf( "hi" );
        }

        putchar( '\n' );

        if ( --n ) star( n );
    }
}

Pay attention to that if the function was called initially with the argument equal to 0 then the function should output nothing.请注意,如果 function 最初调用的参数等于 0,那么 function 应该 output 什么都没有。

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

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