for循环工作,直到我添加printf(在C中)

时间:2013-08-04 14:16:12

标签: c for-loop

我希望这段代码能够打印一个数字因子,如果它不是素数,并且如果它是素数则识别数字。

#include <stdio.h>

main() {
int possible_prime, n, possible_divisor;

printf( "\tThis program lists all primes <= n\n\n" );
printf( "Input n: " );
scanf( "%d", &n );
printf( "\n\n\tPrimes <= %d: \n\n", n );

    for ( possible_prime = 1; possible_prime <= n; possible_prime++ ) {
          /* try to find a divisor of possible_prime */

         for ( possible_divisor = 1; possible_divisor < possible_prime; possible_divisor++ ) {
             if ( possible_prime % possible_divisor == 0 )
                printf("\n\t%d", possible_prime);
               }

          /* found a divisor so possible_prime is not prime */
          break;

    if ( possible_divisor == possible_prime )
         /* exhausted possible divisors, so possible_prime is prime */
         printf( "%d\n", possible_prime );

   }
}

在if语句下面没有printf的情况下工作正常。当我添加它时,程序只打印“Prime数字&lt; = n”而没有别的。我不明白为什么printf会弄乱循环?

2 个答案:

答案 0 :(得分:6)

您的break声明位置错误。把它放在内部for循环中;现在,在检查1是否为素数后,它会突破外部for循环。

至于为什么只有在你添加了内部print语句之后才会发生这种情况,我猜你最终会在这个过程中移动一些花括号。

修好后你可能会发现你的程序告诉你没有什么是素数。您可能想要重新检查程序的素数条件。

答案 1 :(得分:1)

您的程序既不会打印素数,也不会打印非素数的因子。以下是代码的更正版本:

#include <stdio.h>

int main() 
{
    int possible_prime, n, possible_divisor;

    printf( "\tThis program lists all primes <= n\n\n" );
    printf( "\tInput n: " );
    scanf( "%d", &n );
    printf( "\n\n\tPrimes <= %d: \n\n", n );
    printf("Prime num\tNon-prime\n");
    printf("2\n");
    for ( possible_prime = 3; possible_prime <= n; possible_prime++ ) 
    {
            /* try to find a divisor of possible_prime */

            for ( possible_divisor = 2; possible_divisor < possible_prime; possible_divisor++) 
            {
                 if ( possible_prime % possible_divisor == 0 )
                 {
                     printf("\t\t%d:", possible_prime);
                     for (i = 1; i <= possible_prime; i++)
                     {
                         if(possible_prime % i == 0)
                            printf("%d ", i);
                     }
                 printf("\n");  
                 break;
                 }
            }

      /* found a divisor so possible_prime is not prime */


          if ( possible_divisor == possible_prime )
          /* exhausted possible divisors, so possible_prime is prime */
               printf( "%d\n", possible_prime );

    }
}