I have a loop that repeats itself 100 times and every time it generates a random number
Random rnd = new Random();
const double MAX = 42.0;
const double MIN = 34.5;
double ex4 = 0;
for (int i = 0; i < 101; i )
{
double num = rnd.NextDouble() * (MAX - MIN) MIN;
Console.WriteLine("{0:f1}", num);
}
Console.WriteLine("the average of the degres is: {0}",ex4);
And I want to calculate the average of the numbers and print it but I don't know how to store all the values that I could calculate them or if there is another way
CodePudding user response:
Make ex4 a double, not an int.
Inside the loop, ex4 = num;
Print the average as ex4 / 101.
CodePudding user response:
Until now, all answers are telling you how to keep track of all values so that, afterwards, you can take the average.
However, this is not the best approach, the best approach is to keep track of two values:
- The sum of the values
- The amound of the values
Once you have finished your loop, you just divide the sum by the average, and the result is the average.
In pseudo-code:
double sum = 0;
int amount = 0;
for (...)
{
value = random_calculation();
sum = sum value;
amount = amount 1;
}
write_to_output(sum / amount);
This approach is better because you only keep track of 2 values in memory. If you keep track of all values, you occupy 100 memory spaces.
Obviously, for just 100 values, this is neglectable, but imagine you want to do the same for millions of values, you might get into RAM related problems.
CodePudding user response:
Random rnd = new Random();
const double MAX = 42.0;
const double MIN = 34.5;
List<double> results = new List<double>();
for (int i = 0; i < 101; i )
{
double num = rnd.NextDouble() * (MAX - MIN) MIN;
if (num > 36.6 && num< 37.6)
{
}
Console.WriteLine("{0:f1}", num);
results.Add(num);
}
double average = results.Sum() / results.Count;
Console.WriteLine("the average of the degres is: {0}", average);
CodePudding user response:
Random rnd = new Random();
const double MAX = 42.0;
const double MIN = 34.5;
double ex4 = 0;
int iterations=0;
for (int i = 0; i < 101; i )
{
double num = rnd.NextDouble() * (MAX - MIN) MIN;
if (num > 36.6 && num< 37.6)
{
ex4 =num;
iterations ;
Console.WriteLine("{0:f1}", num);
}
}
ex4=ex4/iterations;
Console.WriteLine("the average of the degres is: {0}",ex4);
`