素数计划

Tay*_*hra 0 c numbers

我想用C语言编写一个程序来接受用户输入,我将无法理解循环的逻辑.

for ( c = 2 ; c <= n - 1 ; c++ )
Run Code Online (Sandbox Code Playgroud)

程序代码如下: -

#include<stdio.h>
#include<conio.h>

void main()
{
   int n, c;

   printf("Enter a number to check if it is prime\n");
   scanf("%d", &n);

   for ( c = 2 ; c <= n - 1 ; c++ )
   {
      if ( n % c == 0 )
      {
         printf("%d is not prime.\n", n);
         break;
      }
   }
   if ( c == n )
      printf("%d is prime.\n", n);

   getch();
}
Run Code Online (Sandbox Code Playgroud)

我使用了for循环,它将结束for循环的语句n - 1.如果我将提供输入,11那么它最终11 - 1 = 10将如何放弃逻辑 if(c == n) { printf("%d", n);

Gri*_*han 6

如果我将提供输入,11那么它最终11 - 1 = 10将如何放弃逻辑 if(c == n) { printf("%d", n);

现在正确理解你的for循环条件:

for ( c = 2 ; c <= n - 1 ; c++ )
              ^^^^^^^^^^^^
              2 <= 11 - 1  -> True   // {for block executes }
              3 <= 11 - 1  -> True   // {for block executes }
                 :
                 :
              9 <= 11 - 1  -> True   // {for block executes }
              10 <= 11 - 1  -> True  // {for block executes }
              11 <= 11 - 1  -> False  breaks //{And Now for block NOT executes}

if (c == n)
    ^^^^^^
   11 == 11 -> True  // {if block executes} 
Run Code Online (Sandbox Code Playgroud)

根据for循环条件c <= n - 1,当c值变为等于时循环中断n.所以,如果n是等于 11循环条件是真c = 2c = 10,在每次迭代中c递增一个(使用c++增量)时c成为11(OT说n),那么情况c <= n - 1变得虚假和循环中断.

在if条件(for循环后)c值与之比较n.那是:

if ( c == n )
//   11 == 11  that is true
Run Code Online (Sandbox Code Playgroud)

for n= 11it变为和c= 11如果condition计算为true并且printf()与if执行相关联.


同样重要的是要理解for循环仅在c = nwhen n是素数时终止,但是如果假设n是非素数,那么for循环将因为for循环中嵌套块中的语句而中断c值更少. n - 1break;if

for( c = 2; c <= n - 1; c++ ) 
{
  if(n % c == 0)<=="for Non-prime `n`, if condition will be true for some `c < n - 1`"
  {  ^^^^^^^^^^^ True 
     printf("%d is not prime.\n", n);
     break; <== "move control outside for-loop"
  }  //      | 
}    //      |
// <---------+ // if break; executes control moves here with c < n - 1
if (c == n)<== "this condition will evaluates FALSE"  
   ^^^^^^^^ False
Run Code Online (Sandbox Code Playgroud)

例如,如果n = 8那么在for循环的第一次迭代中使用值,c = 2如果条件if(n % c == 0)计算为if(8 % 2 == 0)== if( 0 == 0)= True并且break;语句内部if-block将控制移到for循环之外(如图所示).

因为循环没有因为c <= n - 1条件而被终止但由于if(n % c == 0)这样的外侧for循环c值而被制动的 这个时间小于n因此 if (c == n)评估为False.