C - Creating functions that return values


The following code illustrates a function that is sent a value and then returns another value.

The convert() function accepts a Fahrenheit value and returns its Celsius equivalent.


#include <stdio.h> 

float convert(float f); 

int main() /*from  w  ww . j  av a 2 s .c o  m*/
   float temp_f,temp_c; 
   printf("Temperature in Fahrenheit: "); 
   temp_c = convert(temp_f); 
   printf("%.1fF is %.1fC\n",temp_f,temp_c); 

float convert(float f) 
   float t; 

   t = (f - 32) / 1.8; 


The convert() function's prototype requires a floating-point value and returns a floating-point value.

The convert() function returns value is stored in variable temp_c.

printf() displays the original value and the conversion.

The .1f placeholder is used. It limits floating-point output to all numbers to the left of the decimal, but only one number to the right.

The convert() function uses two variables: f contains the value passed to the function, a temperature in Fahrenheit.

A local variable t is used to calculate the Celsius temperature value.

The function's result is sent back by using the return keyword.

Related Topic