Exercise: RandomSensor_nopoly
(Non-Polymorphic)¶
Requirement¶
Implement a sensor class RandomSensor_nopoly
which does not access
any real hardware, but rather returns a random temperature within a
given range.
#include <gtest/gtest.h>
#include <sensor-random-nopoly.h>
TEST(sensor_random_suite, basic)
{
RandomSensor_nopoly rs(36.4, 42.3); // <--- give measurements between lo and hi
double t = rs.get_temperature();
ASSERT_GE(t, 36.4); // <--- greater equal to lo
ASSERT_LE(t, 42.3); // <--- less equal to hi
ASSERT_FLOAT_EQ(rs.low(), 36.4); // <--- RandomSensor specific interface
ASSERT_FLOAT_EQ(rs.high(), 42.3); // <--- RandomSensor specific interface
}
Implementation Hint: Randomicity In C++¶
The following program demonstrates how to generate uniformly distributed random
double
values in a specified range.
#include <random>
#include <iostream>
int main()
{
// setup how we want our random numbers to be created (think:
// object initialization)
double lo = 36.1;
double hi = 42.7;
// object state. think: what does the object need during runtime?
std::random_device rd; // <--- /dev/random, used to obtain a seed
std::default_random_engine engine(rd()); // <--- init (and seed) RNG
std::uniform_real_distribution<double> distribution(lo, hi); // <--- tailor desired distribution
// draw 10 random numbers (think: measure temperature)
for (int i=0; i<10; i++) {
double number = distribution(engine); // <--- use uniform_real_distribution to
// draw a number from engine
// and bend it to desired range
std::cout << number << std::endl;
}
return 0;
}
Implementation Hint: Initializer Lists¶
See Constructors: Member Initialization for how to initialize members in an initializer list.