Go Down

### Topic: calculating average from the input (Read 499 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);    }  }} `

#1