We have already learned about several operators for numbers:
+, -, * addition, subtraction, and multiplication (integers and floats)
/ integer division for integers and floating point division for floats
% remainder (modulus) of an integer division
Next, we’ll learn about relational and equality operators that serve to compare the values of two quantities:
<, > less than and greater than operators
<=, >= less than or equal to, greater than or equal to
!= not equal to
== equal to (note the double equal sign; the single equal sign = has already been ’used up’ for our assignment operator)
Investigate9.1.
Which of the following variables would C interpret as "true"? For example, if each variable was placed in the following code’s if statement as "variable", would the program output "True" or "False"?
int a = -1
char b = 'b'
float c = 0.0
int d = 4000
if (variable){
printf("True")
}
else{
printf("False")
}
A true logical relation evaluates to 1, whereas a false relation evaluates to 0. Examples:
Suppose x has the value 3.5. Then (x <= 5.0) evaluates to 1.
Suppose next that x has the value 7. Then (x <= 5.0) evaluates to 0.
(age == 30) evaluates to 1 if indeed age has the value 30, otherwise it evaluates to 0.
Note: Instead of (x <= 5.0) you could also write (5.0 >= x), and instead of (age == 30) you could just as well write (30 == age).
Investigate9.2.
Does the following statement, which is comparing two characters, evaluate to true or false, according to C?
('A' > 'a')
Let’s look at an example.
If you cannot see this codecast, please click here.
Check Your UnderstandingCheck Your Understanding
1.
You are writing a C program that calculates the price of a rental car, depending on how many miles the user wants to drive. If the user drives less than 50 miles then the price of the car is a flat fee of $40. If on the other hand the user drives 50 or more miles, then the cost is computed as $0.70 per mile plus a handling fee of $5.
Please complete the following C program: After the user has entered the number of miles they wish to drive, the program should output the price of the rental car in dollars (with two decimal places).