考虑下面的C程序段。
while (first <= last)
{
if (array [middle] < search)
first = middle +1;
else if (array [middle] == search)
found = True;
else last = middle – 1;
middle = (first + last)/2;
}
if (first < last) not Present = True;
程序段的循环复杂度为__________。
(A) 3
(B) 4
(C) 5
(D) 6答案: (C)
说明:结构化程序[a]的循环复杂度是参照程序的控制流程图定义的,有向图包含程序的基本块,如果控制可能从第一个传递过来,则两个基本块之间会有一条边到第二。然后将复杂度M定义为
M = E − N + 2P,
where
E = the number of edges of the graph.
N = the number of nodes of the graph.
P = the number of connected components.
资料来源:http://en.wikipedia.org/wiki/Cyclomatic_complexity
对于单个程序(或子例程或方法),P始终等于1。因此,单个子例程的更简单公式为
M = E − N + 2
对于给定的程序,控制流程图为:
E = 13, N = 10.
Therefore, E - N + 2 = 5.
这个问题的测验