Как исправить ошибку C # cs0103 в Visual Studio 2017? - PullRequest
0 голосов
/ 11 декабря 2018

Я работаю над проектом, который создает простой калькулятор периметра и площади на основе значений, введенных пользователем.(Для нахождения периметра окна и площади стекла).Тем не менее, я застрял с 4 ошибками ... все из которых являются CS0103.Может ли кто-нибудь помочь мне исправить эти ошибки или очистить мой код.Я пытаюсь разделить все на методы, поэтому я хотел бы сохранить код в этом общем формате.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            double totalLength, totalWidth, windowPerimeter, glassArea;

            //display instructions
            DisplayInstructions();

            // ask for width
            totalWidth = AskDimension();

            //ask for lenght
            totalLength = AskDimension();

            // calculate window Perimeter
            windowPerimeter = (2 * totalWidth) * (2 * totalLength);

            //calculate the area of the window & display output
            glassArea = totalWidth * totalLength;

            //calculate and display outputs

            Console.WriteLine("the lenth of the wood is " + windowPerimeter + " feet");
            Console.WriteLine("the area of the glass is " + glassArea + " square feet");
            Console.ReadKey();

            Console.ReadKey();
        }

        //display instructions
        public static void DisplayInstructions()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("This app will help you calculate the amount of wood and glass needed for your new windows!");
            Console.WriteLine("   ");
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("*Note* Please enter a height/width value between 0.01 - 100, all other values will cause a system error.");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("   ");
        }

        //ask for width
        public static double AskDimension()
        {
            double totalWidth;
            const double MAX_HEIGHT = 100.0;
            const double MIN_Height = 0.01;
            string widthString;
            Console.WriteLine("please enter your height of the window");
            widthString = Console.ReadLine();
            totalWidth = double.Parse(widthString);
            if (totalWidth < MIN_Height)
            {
                Console.WriteLine("you enter vaule less than min width \n" + "using minimum one");
                totalWidth = MIN_Height;
            }
            if (totalWidth > MAX_HEIGHT)
            {
                Console.WriteLine("you enter value grater than Max height\n" + "using maximum one");
                totalWidth = MAX_HEIGHT;
            }

            return AskDimension();
        }

        //ask for height
        public static double AskDimension(string dimension)
        {
            double totalLength;
            const double MAX_HEIGHT = 100.0;
            const double MIN_Height = 0.01;
            string heightString;
            Console.WriteLine("please enter your height of the window");
            heightString = Console.ReadLine();
            totalLength = double.Parse(heightString);
            if (totalLength < MIN_Height)
            {
                Console.WriteLine("you enter vaule less than min width \n" + "using minimum one");
                totalLength = MIN_Height;
            }
            if (totalLength > MAX_HEIGHT)
            {
                Console.WriteLine("you enter value grater than Max height\n" + "using maximum one");
                totalLength = MAX_HEIGHT;
            }

            return AskDimension();
        }
        //calculate and display outputs
        public static double AskDimesnion(string windowPerimeter,
                                          string glassArea,
                                          string widthString,
                                          string heightString)

        {

            windowPerimeter = 2 * (totalWidth + totalLength);
            glassArea = (totalWidth * totalLength);
            Console.WriteLine("the lenth of the wood is " + windowPerimeter + " feet");
            Console.WriteLine("the area of the glass is " + glassArea + " square feet");
            Console.ReadKey();
            return AskDimension();
        }
}
}

Снимок экрана ошибок метода: Screenshot of errors in the method

Ответы [ 2 ]

0 голосов
/ 11 декабря 2018

Первоначальная проблема состояла в том, что ваши переменные не были ограничены классом, а также вычисления кажутся мне немного сумасшедшими.Но после вставки вашего кода в мой редактор я быстро прибегнул и получил следующее:

using System;

namespace TestConsoleApplication
{
    class Program
    {
        static double _totalLength, _totalWidth, _windowPerimeter, _glassArea;

        static void Main(string[] args)
        {
            DisplayInstructions();
            _totalWidth = AskDimension("Height");
            _totalLength = AskDimension("Width");
            _windowPerimeter = (2 * _totalWidth) + (2 * _totalLength);
            _glassArea = _totalWidth * _totalLength;
            Console.WriteLine("The length of the wood is " + _windowPerimeter + " feet");
            Console.WriteLine("The area of the glass is " + _glassArea + " square feet");
            Console.ReadKey();
        }

        private static void DisplayInstructions()
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine("This app will help you calculate the amount of wood and glass needed for your new windows!");
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("*Note* Please enter a height/width value between 0.01 - 100, all other values will cause a system error.");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine();
        }

        private static double AskDimension(string dimensionType)
        {
            const double maxDimension = 100.0;
            const double minDimension = 0.01;

            Console.WriteLine($"Please enter your {dimensionType} of the window");

            var dimensionString = Console.ReadLine();
            var dimension = double.Parse(dimensionString);

            if (dimension < minDimension)
            {
                DisplayDimensionErrorAndExit("Min");
            }
            else if (dimension > maxDimension)
            {
                DisplayDimensionErrorAndExit("Max");
            }

            return dimension;
        }

        private static void DisplayDimensionErrorAndExit(string dimensionToShow)
        {
            Console.WriteLine($"You entered a value less than {dimensionToShow} dimension");
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            Environment.Exit(0);
        }
    }
}

Если пользователь введет неверный ввод, программа будет завершена, кроме того, что вычисления будут работатьи правильный вывод отображается.Если у вас есть какие-либо вопросы по этому поводу, просто спросите меня: -)

0 голосов
/ 11 декабря 2018

Ваша переменная totalWidth не определена нигде в вашей области видимости.Это должно быть определено где-то.В зависимости от того, где именно вы хотите его определить, вы можете сделать это внутренне в вашем методе AskDimension или более глобально.По вашей логике это должен быть входной параметр вашего метода .Также у вас есть другие ошибки в вашем коде.Ваш метод называется AskDimesnion , но вы вызываете его в своем коде как AskDimension (возможно, правильное имя метода ...)

Для переменной области вы можете проверить собственную документацию Microsoft

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...