Home > database >  Center text output from a loop
Center text output from a loop

Time:09-27

I'm working on a temperature converter, at the end the program has to put out Fahrenheit to Celsius or vice versa in an arranged way, like the image here

Example

meaning the C, F and = have to be aligned on each row, I tried string.Format but it only gives me errors.

 for (Farenheit = 0; Farenheit <= maxFarenheit; Farenheit = Farenheit   5)
        {
            Celsius = 5 / 9.0 * (Farenheit - 32);
            Celsius = Math.Round(Celsius, 2);
            Console.WriteLine(Farenheit   " F = "   Celsius   " C");
        }

This the loop

CodePudding user response:

If you want

  0.00 C =  32.00 F
  4.00 C =  39.20 F
  8.00 C =  46.40 F
 12.00 C =  53.60 F
 16.00 C =  60.80 F
 20.00 C =  68.00 F
 24.00 C =  75.20 F
 28.00 C =  82.40 F
 32.00 C =  89.60 F
 36.00 C =  96.80 F
 40.00 C = 104.00 F
 44.00 C = 111.20 F
 48.00 C = 118.40 F

The use format specifies a column width inside an interpolated string. This is done with $"{value,width:format}". See the example code below:

Since this is C# and object-oriented in makes sense to create a class to handle the math.

public class Temperature
{
    public float Celsius { get; set; }
    public float Farenheit
    {
        get
        {
            return 32f   (9f * Celsius) / 5f;
        }
        set
        {
            Celsius = 5f * (value - 32F) / 9F;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Temperature temperature = new Temperature();
        for (int i = 0; i <= 12; i  )
        {
            temperature.Celsius = 4f * i;

            Console.WriteLine($"{temperature.Celsius,6:F2} C = {temperature.Farenheit,6:F2} F");
        }
    }
}

An improvement can be made to include the string formatting inside the class, as in the code below with identical results.

public class Temperature
{
    public float Celsius { get; set; }
    public float Farenheit
    {
        get
        {
            return 32f   (9f * Celsius) / 5f;
        }
        set
        {
            Celsius = 5f * (value - 32F) / 9F;
        }
    }
    public override string ToString()
    {
        return $"{Celsius,6:F2} C = {Farenheit,6:F2} F";
    }
}

class Program
{
    static void Main(string[] args)
    {
        Temperature temperature = new Temperature();
        for (int i = 0; i <= 12; i  )
        {
            temperature.Celsius = 4f * i;

            Console.WriteLine(temperature);
        }
    }
}

The key here is to override the ToString() function that the system uses to convert an object to a string value. It is called automatically by the Console.WriteLine() function and the point is that all formatting can be handled internally from the class.

  •  Tags:  
  • c#
  • Related