The last exercise in chapter 5, 5-8.
Requirements:
/* Enter an Fahrenheit temperature. Read the temperature value in double type and pass it as a parameter to the user's provided function temperatures (). This function calculates the corresponding temperature in Celsius and absolute temperature, and displays the three temperature values with two digits to the right of the decimal point. It should mark the three values with the temperature scale represented by each value. Celsius = 1.8 * Fahrenheit + 32.0 Kelvin = Celsius + 273.16 */
At first, I wrote the following code:
Use gets () to obtain the input string, and then compare whether the first character is a number to determine whether the input is legal. Then use the sscanf () function to read the number in the input string.
#include <stdio.h>void Temperatures(double Fahrenheit);int main(void){double tmp;char str[20];printf("Enter a temperature in Fahrenheit:\n");gets(str);while (str[0] >= ‘0‘ && str[0] <= ‘9‘){sscanf(str,"%lf", &tmp);Temperatures(tmp);printf("Enter a temperature in Fahrenheit:\n");gets(str);}return 0;}void Temperatures(double Fahrenheit){float Celsius, Kelvin;Celsius = 1.8 * Fahrenheit + 32.0;Kelvin = Celsius + 273.16;printf("%.2f %.2f %.2f", Fahrenheit, Celsius, Kelvin);}
Later, it was found that the code could be simplified if the return value of scanf () was used as a judgment.
The Return Value of the scanf () function is the number of successfully read projects. If no project is read, the return value is 0.
Simplified code:
#include <stdio.h>void Temperatures(double Fahrenheit);int main(void){double tmp;printf("Enter a temperature in Fahrenheit:\n");while (scanf("%lf", &tmp)){Temperatures(tmp);printf("Enter a temperature in Fahrenheit:\n");}return 0;}void Temperatures(double Fahrenheit){float Celsius, Kelvin;Celsius = 1.8 * Fahrenheit + 32.0;Kelvin = Celsius + 273.16;printf("%.2f %.2f %.2f", Fahrenheit, Celsius, Kelvin);}