Full Question
Write an expression that will cause the following code to print "Equal" if the value of sensorReading is "close enough" to targetValue. Otherwise, print "Not equal". Ex: If targetValue is 0.3333 and sensorReading is (1.0/3.0), output is: Equal
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double targetValue;
double sensorReading;
cin >> targetValue;
cin >> sensorReading;
if (/* Your solution goes here */) {
cout << "Equal" << endl;
} else {
cout << "Not equal" << endl;
} return 0;
}
Answer:
if (abs(targetValue - sensorReading) <= 0.0001)
Explanation:
Replace
if (/* Your solution goes here */) {
With
if (abs(targetValue - sensorReading) <= 0.0001)
Two values are considered to be close enough if the difference between the values is 0.0001
Splitting the codes into bits;
abs
targetValue - sensorReading
<=
0.0001
The keyword abs is to return the absolute value of the expression in bracket.
This is needed because the expression in the bracket is expected to return a positive value.
To do this the absolute keyword is required.
targetValue - sensorReading returns the difference between the variables
<= compares if the difference falls within range that should be considered to be close enough
0.0001 is the expected range