Data Types
Floating Point
double values store fractional numbers and are printed with floating-point formats.
double
`double` is the usual C type for fractional numeric work.
format
`%.2f` prints a floating-point value with two digits after the decimal point.
Floating Point
floating_point.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
double price = 12.50;
double taxRate = 0.08;
double total = price + price * taxRate;
printf("price=%.2f\n", price);
printf("total=%.2f\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
double price = 10.00;
double taxRate = 0.08;
double total = price + price * taxRate;
printf("price=%.2f\n", price);
printf("total=%.2f\n", total);
return 0;
}
#include <stdio.h>
int main(void) {
double price = 20.00;
double taxRate = 0.08;
double total = price + price * taxRate;
printf("price=%.2f\n", price);
printf("total=%.2f\n", total);
return 0;
}
price ← 12.5, taxRate ← 0.08, total ← 13.5
3int main(void) {4 double price→ 12.5 = 12.50; //@price=10.00, 20.005 double taxRate→ 0.08 = 0.08;6 double total→ 13.5 = price12.5 + price * taxRate0.08;78 printf("price=%.2f\n", price12.5);9 printf("total=%.2f\n", total13.5);10 return 0;11}outputprice=12.50 total=13.50
price ← 10, taxRate ← 0.08, total ← 10.8
3int main(void) {4 double price→ 10 = 10.00;5 double taxRate→ 0.08 = 0.08;6 double total→ 10.8 = price10 + price * taxRate0.08;78 printf("price=%.2f\n", price10);9 printf("total=%.2f\n", total10.8);10 return 0;11}outputprice=10.00 total=10.80
price ← 20, taxRate ← 0.08, total ← 21.6
3int main(void) {4 double price→ 20 = 20.00;5 double taxRate→ 0.08 = 0.08;6 double total→ 21.6 = price20 + price * taxRate0.08;78 printf("price=%.2f\n", price20);9 printf("total=%.2f\n", total21.6);10 return 0;11}outputprice=20.00 total=21.60
Follow the Values
pricestarts at12.50.taxRateis0.08.- The tax is
price * taxRate. total = price + price * taxRatebecomes13.50.- The program prints
price=12.50andtotal=13.50. | price | taxRate | total | | --- | --- | --- | | 10.00 | 0.08 | 10.80 | | 12.50 | 0.08 | 13.50 | | 20.00 | 0.08 | 21.60 |
Exercise: floating_point.c
Reproduce total=13.50, then use price 10.00 and 20.00 to predict each total.