- 论坛徽章:
- 0
|
本来只是想验证一下算法的.无意中遇到的问题
命名不怎么样,写的比较随意,大家将就看吧
- #include <stdio.h>
- /*
- 求任何相邻子向量的最大和,若为负,则返回0
- */
- void C_maxsofar( int a[] );
- void ASM_maxsofar( int a[] );
- void C_maxsofar( int a[] )
- {
- int maxsofar = 0;
- int i = 1;
- int sum = 0;
- for ( i = 1 ; i < a[0]+1; i++ )
- {
- sum += a[ i ];
-
- if ( sum < 0 )
- {
- sum = 0;
- }
- else
- {
- if ( sum > maxsofar )
- {
- maxsofar = sum;
- }
-
- }
- }
- printf( "maxsofar = %d\n",maxsofar );
- }
- void ASM_maxsofar( int a[] )
- {
- int maxsofar;
- __asm
- {
-
- push esi
- push ebx
- push edi
-
- mov eax,0 //sum
- mov ecx,0 //maxsofar
- mov ebx,0
- mov edi,0 //a[0]
- mov ebx,a
- inc esi
- mov edi,[ebx]
-
- begin:
-
- cmp esi,edi
- jg end
- add eax,[ebx+4*esi]
- cmp eax,0
- jg next1
- mov eax,0
- next1:
- cmp ecx,eax
- jg next2
- mov ecx,eax
- next2:
-
- inc esi
- jmp begin
- end:
- mov eax,ecx
-
- pop edi
- pop ebx
- pop esi
- mov maxsofar,ecx
- }
- printf( "maxsofar = %d\n",maxsofar );
-
- }
- int main()
- {
- int item[] = { 10,31,-41,59,26,-53,58,97,-93,-23,84 }; // item[0]存储数组元素个数
- C_maxsofar( item );
-
- ASM_maxsofar( item );
- return 0;
- }
复制代码
如果直接运行的话,则会发现是C_maxsofar得出正确结果,187 , 而ASM_maxsofar得出了错误结果0
跟踪调试,却发现都得出了正确结果187
百思不得其解,优化选项已经全部关了
编译器: VC6.0, XP
[ 本帖最后由 skygram 于 2006-2-14 20:44 编辑 ] |
|