Go Down

Topic: calculating average from the input (Read 429 times)previous topic - next topic

brutal_magnet

Jul 24, 2011, 10:50 am
Hi, I have this program which you will input a number. It will tell whether which digit is the smallest and which is the biggest and this part works fine. What I can't get to work is the average part wherein if I input '1234' it will add 1+2+3+4 and divide the sum by 4. if I run this it gives me an output of '50'. I also need the ave to be in the form of number and not in ascii form. I can't seem to find the problem.Please help.Thanks!

Code: [Select]
`char output[5];int sum=0;void loop(){  if (Serial.available() > 0)  {     delay(10);    int x = 0;    while (Serial.available()>0)    {      output[x] = Serial.read();       output[x+1] = '\0';       x++;     }         if (x>=5 || x<4)    {       Serial.println("The input must be 4 bytes.");     }    else    {      int input = atoi(output);      Serial.print("The value is: ");      Serial.println(input);               Serial.print("1st byte is: ");      Serial.println(output[0]);      Serial.print("2nd byte is: ");      Serial.println(output[1]);      Serial.print("3rd byte is: ");      Serial.println(output[2]);      Serial.print("4th byte is: ");      Serial.println(output[3]);      if (min(output[0],output[1])<min(output[2],output[3]))      {        Serial.print("Byte ");        Serial.print(min(output[0],output[1]));        Serial.println(" is the smallest byte.");      }       else       {        Serial.print("Byte ");        Serial.print(min(output[2],output[3]));        Serial.println(" is the smallest byte.");      }      if (max(output[0],output[1])>max(output[2],output[3]))      {        Serial.print("Byte ");        Serial.print(max(output[0],output[1]));        Serial.println(" is the biggest byte.");      }       else       {        Serial.print("Byte ");        Serial.print(max(output[2],output[3]));        Serial.println(" is the biggest byte.");      }            for (x=0;x<5;x++)      {        sum+=output[x];      }      int ave=sum/4;      Serial.println(ave);    }  }} `

AWOL

#1
Jul 24, 2011, 10:52 am
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

David Pankhurst

#2
Jul 24, 2011, 09:52 pm
You're dealing with numbers and text in the same code, which can be tricky. 1 is one, unless it's the text (ASCII) '1', in which case it's 49. Your average is for the ASCII values, so 50 is almost correct for avg of 1+2+3+4 (it should be 2.5, but integers through away the fraction). One option is to convert ASCII to number as soon as possible, and work with that.

Go Up

Please enter a valid email to subscribe