Loading lessons...
Real-Life Math and Booleans
Real-Life Math and Booleans
Let's put math functions and booleans to work in a small practical program.
Price comparison
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double shopA = 12.50;
double shopB = 11.99;
bool cheapShop = shopA < shopB;
cout << "Shop A is cheaper: " << cheapShop << endl;
return 0;
}
The comparison shopA < shopB is evaluated into a boolean. Cheap shop is a decision the program can make.
Voting age check
int age = 20;
int votingAge = 18;
bool canVote = age >= votingAge;
cout << canVote << endl; // true
A single bool stores the answer for any voter.
Distance with math
cout << sqrt(9) + 1 << endl; // 4
double distance = pow(3, 2) - 5; // 4
cout << (distance > 3) << endl; // true
Keep it readable
- Store the result of a comparison in a
boolvariable. - Use math to compute, booleans to decide.
- Clear names make programs easier to understand.
TL;DR
- Use math functions from
<cmath>in real programs. - Turn comparisons into decisions with booleans.
- Store comparisons in
boolvariables. - Print a bool to see 1 (true) or 0 (false).