An if statement nested in a for loop : break from loop in the second iteration upon condition in if statement 检查

An if statement nested in a for loop : breaking from loop in the second iteration upon reaching condition check in if statement

declaration ( globale ) : 

    struct list
    {
        int v ;
        struct list *suivant ;
    };
    
    int i ;
    struct list *T_list = NULL, *courent = NULL ;

以下函数测试一个数是否为质数; return 1 如果数字是素数,如果不是素数则为 0 :

int est_premier ( int x )
{
    for ( i = x/2 ; i > 1 ; i-- )
    {
        if ( x % i == 0 )
        {
            return 0 ;
        }
    }
    return 1 ;
}

我在以下代码中调用“est_premier”函数并在 if 语句中对其进行测试时遇到问题;该循环应该在 0 和 x(包括 x)之间创建质数链表,发生的情况是代码在到达第二次迭代时立即从循环中中断,而忽略了过程中的 if 语句。

有问题的代码:

void Creer_L ( int x )
{
    for ( i = x ; i > 1 ; i-- )
    {
        if ( est_premier ( i ) == 1 )
        {
            courent = malloc ( sizeof ( struct list ) ) ;
            (*courent).v = i ;
            (*courent).suivant = T_list ;
            T_list = courent ;
        }
    }
}

调用main中的函数:

int main()
{
    Creer_L ( 10 ) ;
    while ( T_list != NULL )
        {
            printf("%d ", (*T_list).v );
            T_list = (*T_list).suivant ;
        }
    return 0 ;
}

输入:10

预期输出:2 3 5 7(0 到 10 之间的素数)

实际输出:(无)

但程序正确终止。

我认为是你的 i 被声明为全局变量并在你的两个循环中使用导致了这种行为。

您可能想在循环中声明它

int est_premier ( int x )
{
    for (int i = x/2 ; i > 1 ; i-- )
    {
        if ( x % i == 0 )
        {
            return 0 ;
        }
    }
    return 1 ;
}

   for ( int i = x ; i > 1 ; i-- )
    {
        if ( est_premier ( i ) == 1 )
        {
            courent = malloc ( sizeof ( struct list ) ) ;
            (*courent).v = i ;
            (*courent).suivant = T_list ;
            T_list = courent ;
        }
    }

并且您可以将其从全局声明中删除,因为您不会在其他任何地方使用它。