我在 C 中使用行內匯編。但是,我的代碼不能正常作業,它總是回傳 0。我想找到一些負值并顯示。你能幫我一下嗎?
PS:我用過除錯但是沒找到問題
void func(const int* arr, size_t arr_rows, size_t arr_cols, int* result)
{
int sum = 0;
_asm
{
mov ebx, [arr] ///address
mov edx, 0; //sum
mov ecx, [arr_rows] // number of rows
row_loop:
push ecx // save number of rows
xor esi, esi // reset column offset for the current row
mov ecx, [arr_cols] // number of column
col_loop :
add ebx, esi;
cmp ebx, 0
jge bigger_case
jl less_case
jmp n_case
less_case :
add esi, 4
add edx, dword ptr[ebx esi];
loop col_loop
bigger_case:
add esi, 4
loop col_loop
n_case:
add esi, 4
add ebx, esi // move to the next row offset
pop ecx // restore row loop counter
loop row_loop;
ending:
mov sum, edx;
}
cout << sum<<" is answer"<<endl;
}
uj5u.com熱心網友回復:
審查
cmp ebx, 0
這會將地址與 0 進行比較。您需要比較陣列中的一個值。
add esi, 4 add edx, dword ptr[ebx esi];
這將下一個元素添加到總和中。您需要當前元素。
loop col_loop <=== This is a 'fall through' bigger_case: add esi, 4 loop col_loop
如果該行的最后一個元素碰巧為負,那么代碼中的這個失敗將開始一個很長的回圈!
jge bigger_case jl less_case jmp n_case less_case :
一旦你知道它既不大于也不等于,那么它就必須小于。在這里,您確實可以理所當然地落入less_case 中。
您可以輕松地對陣列元素進行尋址,而無需使用額外的ESI偏移量。總是add ebx, 4,更干凈。
解決方案
您不需要使用嵌套回圈來解決此任務。只需計算元素總數并使用單個回圈。
xor edx, edx
mov esi, [arr]
mov ecx, [arr_rows]
imul ecx, [arr_cols]
more:
mov eax, [esi]
test eax, eax ; TEST is efficient to inspect the sign
jns skip
add edx, eax ; Only adding negative values
skip:
add esi, 4
dec ecx
jnz more
最好不要使用LOOP指令。請參閱為什么回圈指令很慢?英特爾不能有效地實施它嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/374962.html
