Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.0 KiB

  1. #include <stdio.h>
  2. #include <limits.h>
  3. #include <math.h>
  4. #include <stdbool.h>
  5. double getNumber(char * s);
  6. void calcTemperatures(double fahrenheit);
  7. int main(void) {
  8. double fahrenheit;
  9. printf("This program calculates Celsius & Kelvin from Fahrenheit.\n");
  10. fahrenheit = getNumber("Now enter the temp in Fahrenheit: ");
  11. while (!isnan(fahrenheit)) {
  12. calcTemperatures(fahrenheit);
  13. fahrenheit = getNumber("Now enter the first operand (q to quit): ");
  14. };
  15. return 0;
  16. }
  17. double getNumber(char * s) {
  18. double number;
  19. printf("%s", s);
  20. if (!scanf("%lf", &number) || isnan(number)) {
  21. number = NAN;
  22. }
  23. return number;
  24. }
  25. void calcTemperatures(double fahrenheit) {
  26. const float celsius_div = 5.0 / 9.0;
  27. const float celsius_offset = 32.0;
  28. const float kelvin_offset = 273.16;
  29. const double celsius = celsius_div *(fahrenheit - celsius_offset);
  30. const double kelvin = celsius + kelvin_offset;
  31. printf("%.2lf Fahrenheit are %.2lf Celsius or %.2lf Kelvin.\n", fahrenheit, celsius, kelvin);
  32. }