A exercise in C primer plus

Source: Internet
Author: User

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);}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.