N
N
Newbie22019-01-30 19:15:25
C++ / C#
Newbie2, 2019-01-30 19:15:25

Why is the console not displaying zero when the value of the double variable is less than 1?

Welcome all!
There is this code:

namespace ConsoleApp13
{
    class Program
    {
        static void Main(string[] args)
        {
            double i;
            i = 0.5;
            Console.WriteLine("i равно {0}", i);
        }
    }
}

When you run the program, the number 0.5 is displayed in the console.
But in the code below, instead of "0.5", ".5" is displayed. Zero is not displayed. How can this be corrected?
namespace Technocalc
{
    class Technocalc
    {
        public double S, diameter, L, U, I, R, P, padU;
                
        public double CableResist(double S, double L)
        {
            // public double rConst = 0.018;
            return 0.018/S*L*2;
        }

        public double pad_U (double R, double I, double L)
        {
            return (R * I);
        }
        
    class Calculate
        {

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Technocalc cable = new Technocalc();
            Console.WriteLine("\t\t\t\t" + "Программа расчета падения напряжения в кабеле. 2019 г. Версия 0.0.1");
            bool t;
            t = false;
            while (t == false)
            {
                try
                {
                Console.Write("Введи сечение кабеля, мм2: ");
                    cable.S = Convert.ToDouble(Console.ReadLine());
                    t = true;
                }
            catch (System.FormatException)
                {
                    Console.WriteLine("Ошибка! Разделителем должна быть запятая.");
                }
            }
            t = false;
            while (t == false)
            {
                try
                {
                    Console.Write("Введи длину кабеля, м: ");
                    cable.L = Convert.ToDouble(Console.ReadLine());
                    t = true;
                }
                catch (System.FormatException)
                {
                    Console.WriteLine("Ошибка! Разделителем должна быть запятая.");
                }
            }
            t = false;
            while (t == false)
            {
                try
                {
                    Console.Write("Введи нагрузку на конце линии, А: ");
            cable.I = Convert.ToDouble(Console.ReadLine());
                    t = true;
                }
                catch (System.FormatException)
                {
                    Console.WriteLine("Ошибка! Разделителем должна быть запятая.");
                }
            }
            t = false;
            while (t == false)
            {
                try
                {
                    Console.Write("Введи значение напряжения источника, В: ");
            cable.U = Convert.ToDouble(Console.ReadLine());
                    t = true;
                }
                catch (System.FormatException)
                {
                    Console.WriteLine("Ошибка! Разделителем должна быть запятая.");
                }
            }
            cable.R = cable.CableResist(cable.S, cable.L);
            cable.padU = cable.pad_U(cable.R, cable.I, cable.L);
            cable.diameter = (3.1415926535 * cable.S * cable.S) / 4;

           
            //вывод всей информации на экран
            Console.WriteLine();
            Console.WriteLine("\t\t\t\t"+"Параметры линии:");
            Console.WriteLine("--------------------------------------------------------------------------------");
            Console.WriteLine("Кол-во жил\t\tRкабеля, Ом\t\tСечение, мм2\t\tНапряжение,В\tВых. напряжение, В");
            Console.WriteLine("{0:#.##}\t\t\t{1:#.##}\t\t\t{2:#.##}\t\t\t{3:#.##}\t\t{4:#.##}", 2, cable.R, cable.S, cable.U, cable.U - cable.padU);
            Console.WriteLine("--------------------------------------------------------------------------------");
            Console.WriteLine("Rжилы , Ом\t\tДлина кабеля,м\t\tНагрузка, А\t\tПадение U, В\tДиаметр жилы, мм");
            Console.WriteLine("{0:##.##}\t\t\t{1:##.##}\t\t\t{2:##.##}\t\t\t{3:#.##}\t\t{4:#.##}\t\t", cable.CableResist(cable.S, cable.L)/2, cable.L, cable.I, cable.padU, cable.diameter);
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Foggy Finder, 2019-01-30
@Newbie2

The "#" character in a formatted string does not display "insignificant" zeros. In your case, the "0"
specifier will probably do . You can read more about number formatting, for example, in a special section of the documentation: Custom Numeric Format Strings Let me leave a couple of comments and tips about the code. I wanted to issue it as a comment, but due to the volume and the fact that for some reason the syntax was not highlighted, I transfer it here: 1. As you must have noticed, some functionality is duplicated when reading information from the console. Instead of copying a section of the same type with minimal changes, it is more convenient to put such parts into separate functions. For example:

public static double ReadDouble
    (string msg = "", string errMsg = "Произошла ошибка, повторите ввод")
{
    if (!string.IsNullOrWhiteSpace(msg))
        Console.WriteLine(msg);

    double value;
    while (!double.TryParse(Console.ReadLine(), out value))
        Console.WriteLine(errMsg);

    return value;
}

Then the reading will be much clearer:
var s = ReadDouble("Введи сечение кабеля, мм2: ");
var l = ReadDouble("Введи длину кабеля, мм2: ");
var i = ReadDouble("Введи нагрузку на конце линии, А: ");
var u = ReadDouble("Введи значение напряжения источника, В: ");

2. If possible, you should avoid using "magic numbers" (as you have - 0.018 ). Constants must be defined as constants. Instead of defining Pi as 3.1415926535 , use the built-in Math.PI .
3. The use of fields in the class could be improved. Now they are open and set from the outside. If what parameters are required, then by defining the appropriate constructor, you can not only add to make the class more reliable, but also further check for the correctness of the passed values.
public double S { get; set; }
public double L { get; set; }
public double I { get; set; }
public double U { get; set; }

public Technocalc(double s, double l, double i, double u)
{
    S = s;
    L = l;
    I = i;
    U = u;
}

4. Methods can be simplified with more modern syntax:
public double padU => R * I;
public double R => RConst / S * L * 2;
public double diameter => Math.PI * S * S / 4;

In total, taking into account the above, the class will look like this:
class Technocalc
    {
        public const double RConst = 0.018;

        public double S { get; set; }
        public double L { get; set; }
        public double I { get; set; }
        public double U { get; set; }

        public Technocalc(double s, double l, double i, double u)
        {
            S = s;
            L = l;
            I = i;
            U = u;
        }

        public double padU => R * I;
        public double R => RConst / S * L * 2;
        public double diameter => Math.PI * S * S / 4;
    }

and calling code:
public static double ReadDouble
            (string msg = "", string errMsg = "Произошла ошибка, повторите ввод")
        {
            if (!string.IsNullOrWhiteSpace(msg))
                Console.WriteLine(msg);

            double value;
            while (!double.TryParse(Console.ReadLine(), out value))
                Console.WriteLine(errMsg);

            return value;
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("\t\t\t\t" + "Программа расчета падения напряжения в кабеле. 2019 г. Версия 0.0.1");
            var s = ReadDouble("Введи сечение кабеля, мм2: ");
            var l = ReadDouble("Введи длину кабеля, мм2: ");
            var i = ReadDouble("Введи нагрузку на конце линии, А: ");
            var u = ReadDouble("Введи значение напряжения источника, В: ");
            Technocalc cable = new Technocalc(s, l, i, u);

            //вывод всей информации на экран
            Console.WriteLine();
            Console.WriteLine("\t\t\t\t" + "Параметры линии:");
            Console.WriteLine("--------------------------------------------------------------------------------");
            Console.WriteLine("Кол-во жил\t\tRкабеля, Ом\t\tСечение, мм2\t\tНапряжение,В\tВых. напряжение, В");
            Console.WriteLine("{0:#0.##}\t\t\t{1:0.0#}\t\t\t{2:0.##}\t\t\t{3:0.##}\t\t{4:0.##}", 2, cable.R, cable.S, cable.U, cable.U - cable.padU);
            Console.WriteLine("--------------------------------------------------------------------------------");
            Console.WriteLine("Rжилы , Ом\t\tДлина кабеля,м\t\tНагрузка, А\t\tПадение U, В\tДиаметр жилы, мм");
            Console.WriteLine("{0:#0.##}\t\t\t{1:#0.##}\t\t\t{2:#0.##}\t\t\t{3:#0.##}\t\t{4:#0.##}\t\t", cable.R / 2, cable.L, cable.I, cable.padU, cable.diameter);
            Console.WriteLine();
            Console.ReadKey(true);
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question