使用c++编写一个二分查找函数并且1.画控制流图; 分别确定3条路径,满足100%语句覆盖、完全分支覆盖、 完全谓词覆 盖;并推导出相应路的路径谓词表达式; 求解每个谓词表达式,找出至少一条不可行路径; 引入至少一个缺陷,使得某个特定的满足完全分支覆盖准则的测试用例, 。 试提出一种方法,能检测出前一步引入的缺陷。
时间: 2023-11-22 19:51:50 浏览: 27
二分查找的代码:
```c++
#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int x) {
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] < x)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
int main()
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}
```
控制流图:
![binary search control flow graph](https://i.imgur.com/3xa2yRy.png)
根据控制流图,可以得到三条路径:
- Path 1: 1-2-3-4-5-6-7-8-9-10
- Path 2: 1-2-3-4-5-6-7-11-12-10
- Path 3: 1-2-3-4-5-6-13
对应的路径谓词表达式:
- Path 1: T
- Path 2: arr[mid] < x
- Path 3: arr[mid] > x
我们可以通过修改输入数组,让某个测试用例不可行。例如,将数组改为 `{2, 3, 4, 10, 10, 40}`,此时输入 `x = 10` 时,函数会返回 3,而不是 4。
为了检测出这个缺陷,我们可以引入额外的检查,例如在 while 循环中增加以下代码:
```c++
if (l > r)
return -1;
```
这样,当 l > r 时,函数会直接返回 -1,避免出现错误的结果。我们可以通过修改输入数组,让某个测试用例触发这个检查。例如,将数组改为 `{2, 3, 4, 10, 10, 40}`,此时输入 `x = 50` 时,函数会进入死循环,因为 l 和 r 的值不断交替,无法跳出循环。我们可以在这种情况下,加入一个计数器来记录循环次数,如果超过一定次数就认为进入了死循环,从而判断出这个缺陷。