View previous topic :: View next topic |
Author |
Message |
t90
Joined: 07 Aug 2008 Posts: 11 Location: saigon,vietnam
|
Why can I not compare two arrays of 4 elements ? |
Posted: Wed Dec 03, 2008 9:26 pm |
|
|
The value of my compare function doesn't return the truth value although
I tried every solution but it still doesn't return the right value. Someone please help me!
Here is my code:
First solution:
Code: |
int compare2(int8 a[4],int8 b[4]){
//compare the fourth element first because it storage the highestvalue //in the array,the lowest value is the first element
if(b[3]<a[3]){
return 1;
}else if(b[3]==a[3]){
if(b[2]<a[2]){
return 1;
}else if(b[2]==a[2]){
if(b[1]<a[1]){
return 1;
}else if(b[1]==a[1]){
if(b[0]<a[0]){
return 1;
}else if(b[0]==a[0]){
return 3;
}else
return 2;
}else
return 2;
}else
return 2;
}else
return 2;
}
|
Second solution:
Code: |
int compare2(int8 *a, int8 *b)
{
int index = 3;
for (count = 0; count < 4; count++)
{
if (b[index] < a[index])
return 1; // Less
else if (b[index] > a[index])
return 2; // Greater
index--;
}
return(1); // Equal
}
|
Third solution:
Code: |
int compare2(int8 a[4], int8 b[4])
{
int index = 3;
for (count = 0; count < 4; count++)
{
if (b[index] < a[index])
return 1; // Less
else if (b[index] > a[index])
return 2; // Greater
index--;
}
return(1); // Equal
} |
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
|
Wayne_
Joined: 10 Oct 2007 Posts: 681
|
|
Posted: Thu Dec 04, 2008 9:04 am |
|
|
Hi,
I gave you that second piece of code and I have also told you that I made a couple of mistakes in it. Below is the corrected code which I had already sent you.
Code: |
int compare2(int8 *a, int8 *b)
{
int index = 3;
int count; // This is where the first fault was
for (count = 0; count < 4; count++)
{
if (b[index] < a[index])
return 1; // Less
else if (b[index] > a[index])
return 2; // Greater
index--;
}
return(3); // Equal (This is where the second fault was)
}
|
I have now tested this and sent you my test code which proves that it works.
If you are still having problems with it then feel free to post here or PM me to try and get it sorted.
PCM programmer, Yes there are functions to compare arrays, in paticular strings. What t90 has are 2 arrays of BCD values and he needs to compare in the following order index 3 then index 2 then index 1 and finaly index 0. I found it easier to provide him with this code than try and find a function to do what he wants.
It may be possible that memcmp or even strcmp will give the correct results but it would have taken me longer to work it out LOL
If he was to re-arange his data then the compare functions may provide a better solution, I have no idea if he can do this though!
Anyway, this code does work for what he wants, If he annot get it to work then he must be doing something wrong! |
|
|
|