View previous topic :: View next topic |
Author |
Message |
future
Joined: 14 May 2004 Posts: 330
|
for loop problem |
Posted: Wed Oct 20, 2004 4:45 pm |
|
|
Hi,
I am having this problem that I could not solve by myself.
This code searches through 4 bins to find where given value fits
and interpolates a result based on its findings.
For some reason itps gets a value of 3 when it should not.
Any hints?
Thank you.
Code: | //This interpolates between y1 and y2, result depends on where x
//fits between x1 and x2.
int8 interp(char x,char x1,char x2,char y1,char y2);
const char tpsdt[4] = {0x05, // 2 .
0x14, // 4 ..
0x28, // 8 ...
0x4D}; // 15 volts delta
for(itps=0;itps<3;itps++) // find bin position
{ if(tpsdot<tpsdt[itps+1]) { break; } } //
//
calc=interp(tpsdot, // interpolate result
tpsdt[itps], //
tpsdt[itps+1], //
cfg.tps[itps], //
cfg.tps[itps+1]); // |
|
|
|
Haplo
Joined: 06 Sep 2003 Posts: 659 Location: Sydney, Australia
|
|
Posted: Wed Oct 20, 2004 5:23 pm |
|
|
You are checing the following condition for the itps values of 0, 1 and 2.
Code: |
if (tpsdot<tpsdt[itps+1])
|
So basiaclly you are comparing tpsdot to numbers 0x05,0x14 and 0x28. Now lets say tpsdot assumes a value higher than 0x28 for whatever reason). The above condition will never become true so you will never break out of the for loop. itps will keep increasing until it reaches 3, then the condition inside the for loop (;itps<3;) will cause it to terminate. In this case at the next line itps will be equal to 3. |
|
|
future
Joined: 14 May 2004 Posts: 330
|
|
Posted: Wed Oct 20, 2004 5:47 pm |
|
|
So a simple
Code: | for(itps=0;itps<[b]2[/b];itps++) |
solves all my problems.
Thank you. |
|
|
Haplo
Joined: 06 Sep 2003 Posts: 659 Location: Sydney, Australia
|
|
Posted: Wed Oct 20, 2004 5:59 pm |
|
|
But aware that this is not good coding practice. |
|
|
future
Joined: 14 May 2004 Posts: 330
|
|
Posted: Wed Oct 20, 2004 6:13 pm |
|
|
Do you have any sugestions? |
|
|
Haplo
Joined: 06 Sep 2003 Posts: 659 Location: Sydney, Australia
|
|
Posted: Wed Oct 20, 2004 6:23 pm |
|
|
What is the maximum value tpsdot can have? |
|
|
future
Joined: 14 May 2004 Posts: 330
|
|
Posted: Wed Oct 20, 2004 6:47 pm |
|
|
I will use a maximum value of 77 (0x4D) but it 'can' go up to 255. |
|
|
Haplo
Joined: 06 Sep 2003 Posts: 659 Location: Sydney, Australia
|
|
Posted: Thu Oct 21, 2004 1:01 am |
|
|
Well since your for index can only be 0 and 1, you are not using half of the tpsdt[4] array.
And it is a good idea to put a safeguard there in case the value gets bigger than 0x4D. Something like:
Code: |
if(itps<4)
{
calc=interp(tpsdot, // interpolate result
tpsdt[itps], //
tpsdt[itps+1], //
cfg.tps[itps], //
cfg.tps[itps+1]);
}
else
printf("some error message");
|
|
|
|
|