# celsius to kelvin and vice versa

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 5 Exercise 5
Using std_lib_facilities.h by Bjarne Stroustrup.

[code language=”cpp”]
// Philipp Siedler
// Bjarne Stroustrup’s PP
// Chapter 5 Exercise 5

//input: 24c
//input: 24k

#include "std_lib_facilities.h"

double ctok(double c) {

double lowestTempinC = -273.15;
double highestTempinC = 57.8;
double kelvin = 273.15;

if (lowestTempinC >= c) {
error("Temperature is unrealisticly low: ", c);
}
if (highestTempinC <= c) {
error("Temperature is unrealisticly high: ", c);
}

double k = c + kelvin;

if (k >= (lowestTempinC + kelvin) && k <= (highestTempinC + kelvin)) {
return k;
}
else {
error("post-condition ctok()");
}
}

double ktoc(double k) {

double lowestTempinK = 0;
double highestTempinK = 330.95;
double kelvin = 273.15;

if (lowestTempinK >= k) {
error("Temperature is unrealisticly low: ", k);
}
if (highestTempinK <= k) {
error("Temperature is unrealisticly high: ", k);
}

double c = k – kelvin;

if (c >= (lowestTempinK – kelvin) && c <= (highestTempinK – kelvin)) {
return c;
}
else {
error("post-condition ktoc()");
}
}

int main()
try
{
double value = 0;
string unit;
string s;

cout << "Enter temperature with a c for celsius or k for kelvin, to be converted vis a vis: \n";

if (cin >> value >> unit) {
if(unit == "c"){
double k = ctok(value);
cout << value << " celsius are " << k << " kelvin" << ‘\n’;
}
else if(unit == "k") {
double c = ktoc(value);
cout << value << " kelvin are " << c << " celsius" << ‘\n’;
}
else {
error("unit entered does not exist: ", unit);
}
}

else {
cin.clear();
cin >> s;
error("Illegal input entered: ", s);
}

keep_window_open();
}
catch (runtime_error e) {
cout << e.what() << "\n";
keep_window_open(".");
}
catch (…) {
cout << "Exiting \n";
keep_window_open(".");
}
[/code]

```Output:
Enter temperature with a c for celsius or k for kelvin, to be converted vis a vis:
24c
24 celsius are 297.15 kelvin

Enter temperature with a c for celsius or k for kelvin, to be converted vis a vis:
24k
24 kelvin are -249.15 celsius
```

### One comment

1. Rostyslav

I did it other way:

#include “std_lib_facilities.h”
class wrong_temperature{};
double ctok(double c)

{
if(c<-273.15)
throw wrong_temperature{};
double k=c+273.15;
return k;
}
double ktoc(double ke)
{
if(ke<0)
throw wrong_temperature{};
double ce=ke-273.15;
return ce;
}
int main()
{
cout<>c;
double k=ctok(c);
cout<<"The temperature in Kelvin is "<<k<<'\n';
cout<>ke;
double ce=ktoc(ke);
cout<<"The temperature in Celsius is "<<ce<<'\n';
}