目录

查找给定数字是偶数还是奇数(Find if a given number is even or odd)

找到给定数字是偶数或奇数,是一个经典的C程序。 我们将在C中学习使用条件语句if-else 。

算法 (Algorithm)

这个程序的算法很简单 -

START
   Step 1 → Take integer variable A
   Step 2 → Assign value to the variable
   Step 3 → Perform A modulo 2 and check result if output is 0
   Step 4 → If <u>true</u> print <i>A is even</i>
   Step 5 → If <u>false</u> print <i>A is odd</i>
STOP

流程图 (Flow Diagram)

我们可以绘制这个程序的流程图,如下所示 -

FlowDiagram甚至奇怪

伪代码 (Pseudocode)

procedure even_odd()
   IF (number modulo 2) equals to 0
      PRINT number is even
   ELSE
      PRINT number is odd
   END IF
end procedure

实现 (Implementation)

该算法的实现如下 -

#include <stdio.h>
int main() {
   int even = 24;
   int odd  = 31;
   if (even <b class="notranslate">%</b> 2 == 0)
      printf("%d is even\n", even);
   if (odd <b class="notranslate">%</b> 2 != 0 )
      printf("%d is odd\n", odd);
   return 0;
}

输出 (Output)

该方案的产出应该是 -

24 is even
31 is odd
↑回到顶部↑
WIKI教程 @2018