微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 硬件工程师文库 > 算法需用编程语言很好地实现

算法需用编程语言很好地实现

时间:09-17 来源:电子工程专辑 点击:

ex < length; index++){  

8.         if(value == array[index])  

9.             return index;  

10.     }  

11.   

12.     return FALSE;  

13. }  

上面的代码已经接近完整了,那么测试用例又该怎么编写呢?

1. static void test2()  

2. {  

3.     int array[10] = {1, 2};  

4.     assert(0 == find(array, 10, 1));  

5.     assert(FALSE == find(array, 10, 10));  

6. }  

运行完所有的测试用例后,我们看看对原来的代码有没有什么可以优化的地方。其实,我们可以把数组转变成指针。

1. int find(int array[], int length, int value)  

2. {  

3.     if(NULL == array || 0 == length)  

4.         return FALSE;  

5.   

6.     int* start = array;  

7.     int* end = array + length;  

8.     while(start < end){  

9.         if(value == *start)  

10.             return ((int)start - (int)array)/(sizeof(int));  

11.         start ++;  

12.     }  

13.   

14.     return FALSE;  

15. }  

如果上面的代码参数必须是通用的数据类型呢?

1. template  

2. int find(type array[], int length, type value)  

3. {  

4.     if(NULL == array || 0 == length)  

5.         return FALSE;  

6.   

7.     type* start = array;  

8.     type* end = array + length;  

9.     while(start < end){  

10.         if(value == *start)  

11.             return ((int)start - (int)array)/(sizeof(type));  

12.         start ++;  

13.     }  

14.   

15.     return FALSE;  

16. }  

此时,测试用例是不是也需要重新修改呢?

1. static void test1()  

2. {  

3.     int array[10] = {0};  

4.     assert(FALSE == find(NULL, 10, 10));  

5.     assert(FALSE == find(array, 0, 10));  

6. }  

Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top