131k views
5 votes
Floating-point comparison: Print Equal or Not equal. 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". Hint: Use epsilon value 0.0001. Ex: If targetValue is 0.3333 and sensorReading is (1.0/3.0), output is: Equal

#include
#include
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;
}

User Ishmeet
by
8.6k points

1 Answer

5 votes

Final answer:

To determine if the value of sensorReading is close enough to targetValue, we can use the expression (abs(sensorReading - targetValue) < 0.0001). If the difference between the two values is less than the epsilon value of 0.0001, the code will print "Equal". Otherwise, it will print "Not equal".

Step-by-step explanation:

To determine if the value of sensorReading is close enough to targetValue, we can use the following expression:



(abs(sensorReading - targetValue) < 0.0001)



The abs() function is used to calculate the absolute value, and the expression (sensorReading - targetValue) < 0.0001 will return true if the difference between the two values is less than the epsilon value of 0.0001.



Here is the modified code:



#include <iostream>
using namespace std;

int main() {
double targetValue;
double sensorReading;

cin >> targetValue;
cin >> sensorReading;

if (abs(sensorReading - targetValue) < 0.0001) {
cout << "Equal" << endl;
}
else {
cout << "Not equal" << endl;
}

return 0;
}

User Luis Candanedo
by
8.1k points