[Solved] Temperature table using for loop c++ [closed]


You can use some user defined functions to calculate the conversion from Celsius to the other units.

Then you only need one loop:

#include <iostream>
#include <iomanip>

using std::cout;
using std::cin;
using std::setw;

// define some constant
const double zero_point = 273.15;
constexpr double factor = 9.0 / 5.0;
const double max_cels = 5000;

// farenheit conversion
double cels_to_far( double cels ) {
    return cels * factor + 32.0;
}

// kelvin conversion
double cels_to_kel( double cels ) {
    return cels + zero_point;
}

// rankine conversion
double cels_to_ran( double cels ) {
    return ( cels + zero_point ) * factor;
}

int main()
{
    double temp_cels;
    double delta_t;

    cout << "Enter the temperature in celsius: ";
    cin >> temp_cels;
    while ((temp_cels < -zero_point) || (temp_cels > 5000)) {
        cout << "ERROR: out of range.\n";
        cout << "Enter the temperature in celsius: ";
        cin >> temp_cels;
    }
    cout << "Enter the increment value: ";
    cin >> delta_t;
    cout << "\n         #      Cels      Fahr       Kel      Rank\n";

    // output loop
    for ( int i = 0; i < 20; ) { 
        cout << setw(10) << ++i << std::fixed << std::setprecision(2)
            << setw(10) << temp_cels 
            << setw(10) << cels_to_far(temp_cels) 
            << setw(10) << cels_to_kel(temp_cels)
            << setw(10) << cels_to_ran(temp_cels) << std::endl;
        temp_cels += delta_t;
    }
}

The output is as expected ( 50° Celsius and increment of 5°):

 #      Cels      Fahr       Kel      Rank
 1     50.00    122.00    323.15    581.67
 2     55.00    131.00    328.15    590.67
 3     60.00    140.00    333.15    599.67
 4     65.00    149.00    338.15    608.67
 5     70.00    158.00    343.15    617.67
 6     75.00    167.00    348.15    626.67
 7     80.00    176.00    353.15    635.67
 8     85.00    185.00    358.15    644.67
 9     90.00    194.00    363.15    653.67
10     95.00    203.00    368.15    662.67
11    100.00    212.00    373.15    671.67
12    105.00    221.00    378.15    680.67
13    110.00    230.00    383.15    689.67
14    115.00    239.00    388.15    698.67
15    120.00    248.00    393.15    707.67
16    125.00    257.00    398.15    716.67
17    130.00    266.00    403.15    725.67
18    135.00    275.00    408.15    734.67
19    140.00    284.00    413.15    743.67
20    145.00    293.00    418.15    752.67

solved Temperature table using for loop c++ [closed]