1

I have this simple function that produces 2 float values sum and product from which i calculate another varaible NodePrio. I had the value of NodePrio coming wrong so i decided to put in some console debug messages to read these values as they were being modified in the loop Here is the code

void cycPrioCalc(){
float sum = 0.0, product = 1.0;
for (int i = 0; i< 4; i++){
    if (loads[i].state == LOW){
        if (loads[i].dynPrio > 1.0){
            loads[i].dynPrio -= Pstep;
        }
        if (loads[i].dynPrio < 1.0){    // stop overshoot
            loads[i].dynPrio = 1.0;
        }
    }

    else if (loads[i].state == HIGH){
        if (loads[i].dynPrio < loads[i].fixPrio){
            loads[i].dynPrio += Pstep;
        }
        if (loads[i].dynPrio > loads[i].fixPrio){    // stop overshoot
            loads[i].dynPrio = loads[i].fixPrio;
        }
    }
    // CAlculate the priority of the node
    sum += loads[i].dynPrio;
    Serial.print(sum);
    Serial.print("\n");
    product *= loads[i].dynPrio;
    Serial.print(product);
    Serial.print("\n");
}
NodePrio = product / sum;
}

The values for loads[i].dynPrio goes 1.0, 2.0,3.0 and 4.0 for the 4 elements of the loop. so according to this logic at the end of the loop sum should be 1.0+2.0+3.0+4.0 = 10.0 and product should be 1.0 * 2.0 * 3.0 * 4.0 = 24.0

and NodePrio should be __ 24.0 / 10.0 = 2.40 __

strangely, what i receive in serial output are the last values that were computed,

** sum = 4.0** and ** product = 1.0 ** thus setting **NodePrio = 0.25 **

here is the serial output

1.00    -> Sum at  i=0
1.00    -> Product at  i=0
2.00    -> Sum at  i=1
1.00    -> Product at  i=0
3.00    -> Sum at  i=2
1.00    -> Product at  i=0
4.00    -> Sum at  i=3
1.00    -> Product at  i=0
0.25    -> NodePrio

First place to look was the braces, which look fine to me. All help is apprecieated.

7
  • You're adding 1 each time. What did you expect to be multiplying by? – Ignacio Vazquez-Abrams Dec 5 '14 at 19:42
  • Add more debugging output -- specifically loads[i].dynPrio and loads[i].state they are probably not what you expect. – Craig Dec 5 '14 at 22:03
  • @IgnacioVazquez-Abrams, i did not get you, i only added the element loads[i].dynPrio to the sum and multiplied it to product, can you please point where in my code you observed this "addding 1 each time" – ArunMKumar Dec 5 '14 at 23:51
  • @Craig, loads is a structure with initialized members and also, the values that sum assumes, i.e 1.0, 2.0, 3.0 and 4.0 are actually values of loads[0---4].dynPrio. – ArunMKumar Dec 5 '14 at 23:52
  • Your sum goes up by 1 each time. Which means that you're adding 1. – Ignacio Vazquez-Abrams Dec 5 '14 at 23:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.