25 March 2010

Task 36 - Generate 100 random numbers 0-9, calculate their Mean (average), & output the result to the Serial Monitor

/*
* Project: Random-numbers_task_36
* Author: Jane-Maree Howard
* Date: Thursday 25/03/2010
* Platform: Arduino 18
* Purpose: To generate 100 random numbers from 0-9 inclusive,
* label them 1-100 & output them to the
* Serial Monitor (SM), along with their average (mean)
*/

long randNumber; //random number to SM
float theMean; // will be the Mean of all 100 numbers

//set up random number seed & baud rate to SM
void setup()
{
Serial.begin(9600);
randomSeed(analogRead(0));
}//end setup()

//generates 100 random numbers 0-9 inclusive
void loop()
{
Serial.println("\n100 random numbers\n------------------");
delay(150);
theMean = 0; // initialise 'theMean'
for (int j=1; j<=100; j++) { randNumber = random(10); // random number from 0-9.. // ..& add to the total of the 100 numbers.. theMean = theMean + randNumber; Serial.print(j); Serial.print(".\t"); Serial.println(randNumber); delay(10); }//for (j++) //..now calculate the Mean (average) of the 100 random numbers.. theMean = theMean/100; Serial.print("~~~~~~~~~~~~\nMean\t"); //..& print it to the SM Serial.println(theMean); Serial.println("~~~~~~~~~~~~"); /* NOTE: theMean is a 'float'ing point number; using an 'int' or 'long' produces a rounding with no decimal places */ delay(500); //now repeat the cycle.. }//end loop()

1 comment:

  1. The Mean defaults to 2 decimal places.
    It must be a 'float' number, since 'int' or 'long' will produce Rounding (i kept getting either 4 or 5 before i changed this)

    ReplyDelete