Modifying a Code Statement Below

Good day to everyone. I have found a code statement regarding the temperature converter. Thanks to http://www.trytoprogram.com/cpp-examples/cplusplus-program-to-convert-temperature. I have been wondering how to modify the particular code below by implementing a function statement on it. Can someone lend me a hand with this? Thanks.

I'm still a newbie and still learning about functions. I just need a reference in order to understand functions more fully.

//C++ program for converting degree Celsius into Fahrenheit and vice versa
#include<iostream>
using namespace std;

int main()
{
float fahr, cel;
char option;

cout << "Choose from following option:" << endl;
cout << "1. Celsius to Fahrenheit." << endl;
cout << "2. Fahrenheit to Celsius." << endl;
cin >> option;

//option for converting celsius into fahernheit
if (option == '1')
{
cout << "Enter the temperature in Celsius: ";
cin >> cel;

fahr = (1.8 * cel) + 32.0; //temperature conversion formula
cout << "\nTemperature in degree Fahrenheit: " << fahr << " F" << endl;
}
//option for converting Fahrenheit into Celsius
else if (option == '2')
{
cout << "Enter the temperature in Fahrenheit: ";
cin >> fahr;

cel = (fahr - 32) / 1.8; //temperature conversion formula
cout << "\nTemperature in degree Celsius: " << cel << " C" << endl;
}
else
cout << "Error Wrong Input." << endl;

return 0;
}
Last edited on
take the computation: fahr = (1.8 * cel) + 32.0;

and make a function from that. in a sense c++ functions are like math functions, y=f(x).
1
2
3
4
5
6
7
8
9
10
11
12
13
double CtoF(double C) //type function_name(parameters)
{
    return (1.8 * C) + 32.0;
}
...
main..
{
  blah blah
  cout << CtoF(cel);
  or
  fahr = CtoF(42.0);
  and so on.
}


give this a read: https://www.cplusplus.com/doc/tutorial/functions/
Last edited on
Chapter 2 at "Learn C++" is all about functions. Start here: https://www.learncpp.com/cpp-tutorial/introduction-to-functions/

BTW,
PLEASE learn to use code tags, they make reading and commenting on source code MUCH easier.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

HINT: you can edit your post and add code tags.

Some formatting & indentation would not hurt either
Topic archived. No new replies allowed.