C - Creating functions that return values

Introduction

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.

Demo

#include <stdio.h> 

float convert(float f); 

int main() /*from   www.java  2  s . c  o m*/
{ 
   float temp_f,temp_c; 
   printf("Temperature in Fahrenheit: "); 
   scanf("%f",&temp_f); 
   temp_c = convert(temp_f); 
   printf("%.1fF is %.1fC\n",temp_f,temp_c); 
   return(0); 
} 

float convert(float f) 
{ 
   float t; 

   t = (f - 32) / 1.8; 
   return(t); 
}

Result

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