首页 > 解决方案 > Celsius to Fahrenheit and Fahrenheit to Celsius table (C++)

问题描述

I am making a table that consists of celsius values that convert to Fahrenheit and the other way around as well.

This is what I want the code to output:

Celsius       Fahrenheit     |   Fahrenheit       Celsius
40.0           104.0         |     120.0           48.89
39.0           102.2         |     110.0           43.33

The problem is that with the functions I cannot get the second part to output on the other side of the table.

This is what the code outputs (not what I want):

Celsius       Fahrenheit     |   Fahrenheit       Celsius
40.0           104.0         |     
39.0           102.2         |     
120.0           48.89
110.0           43.33

this is the code I have

#include <iostream>
#include <math.h>
#include <string>
#include <iomanip>

using namespace std;

double celsiusToFahrenheit(double f1);
double fahrenheitToCelsius(double c2);

int main(){

    double f1;

    double c2;

    cout<< left <<setw(10)<< left << "Celsius" << right<< setw(10) << "Fahrenheit | " << setw(10) << "Fahrenheit" << right << setw(10)<< "Celsius"<< endl;

    cout<< left<< setw(10)<< left << celsiusToFahrenheit(f1) << right << setw(10)<< fahrenheitToCelsius(c2)<< endl;
    


    return 0;
}

double celsiusToFahrenheit(double f1){


for(double c1 = 40.0; c1 > 30.00; c1--){
        
        f1 = (c1 * (9.0/5.0)) + 32.0;

       cout<< left <<setw(10)<< left << c1<< right<< setw(10) << f1 << right<<" | "<< endl;
    }

    return f1;

}

double fahrenheitToCelsius(double c2){


for(double f2 = 120.0; f2 > 29.00; f2--){
        
         c2 = ((5.0/9.0) * (f2 - 32.0));

         cout<< left <<setw(10)<< left << f2<< right<< setw(10) << c2 << right<< endl;

    }


    return c2;

}

标签: c++functionmethodsdoubleconverters

解决方案


在正在打印的东西内部进行打印可能是这里出了问题的地方,尤其是endl在这些函数内部。

你提前切断了线路。快速解决方法是摆脱它:

cout<< left <<setw(10)<< left << c1<< right<< setw(10) << f1 << right<<" | ";

然而,这里的问题是您在打印这些内容的过程中进行迭代,这会导致大量的结构性问题。


推荐阅读