CS 102
Notes for Tuesday 1 February
- Meeting 5
- read §4.1–4.2
Boolean expressions, logical operators, if, and else.
(We're one lecture behind, so above topics will be covered in Meeting 6.)
Table of Contents
1 Assignment 2 solution
#include <stdio.h>
int main1()
{
float temp_f, temp_c;
temp_f = 71.5;
temp_c = (temp_f-32)/1.8f;
printf("%f degrees Fahrenheit is"
" %f degrees Celsius.\n",
temp_f, temp_c);
return 0;
}
2 Formatted Output
We learned about %f and %d format codes for printf. These are
used to output floats and integers, respectively. But they have a
few more features for formatted output. By default, for example,
our float values were printing out with six digits after the
decimal:
printf("The answer is %f\n", 3.4);
// Result: The answer is 3.400000
2.1 Digits after decimal
It's possible to specify how many digits you want after the
decimal point, just by modifying the format code. For example,
%.2f will round off after two digits:
printf("The answer is %.2f\n", 2.3491);
// Result: The answer is 2.35
2.2 Field width
2.3 More examples
#include <stdio.h>
int ()
{
printf("==%6.1f==\n", 358.26);
printf("==%3.0f==\n\n", 15.9);
printf("milk %5.2f\n", 2.49);
printf("bread %5.2f\n", 3.86);
printf("candy %5.2f\n\n", 25.99);
printf("Amount: %09.2f\n\n", 350.46);
return 0;
}
3 Formatted Input
#include <stdio.h>
int main()
{
float temp_f, temp_c;
printf("Enter temperature (F): ");
scanf("%f", &temp_f);
temp_c = (temp_f-32)/1.8f;
printf("%.2f degrees Fahrenheit is"
" %.0f degrees Celsius.\n",
temp_f, temp_c);
return 0;
}