我的第一个计算器

时间:2016-10-13 06:04:15

标签: c# calculator

所以我刚刚开始学习编码,已经进行了大约1周。我想尝试制作一个+和 - 的计算器,但是无法弄清楚如何让用户选择他想要使用的东西,是否有人可以帮助我? 这是代码。

        int x;
        int y;
        Console.WriteLine("Welcome to my calculator program!");
        Console.WriteLine("This calculator for now can only do + and -");
        Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +");

        Console.WriteLine("pls write in you x");
        x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("pls write in your y");
        y = Convert.ToInt32(Console.ReadLine());

        if (x > y)
        {
            Console.WriteLine("you chose to use minus");
            int sum = x - y;
            Console.WriteLine("result: {0}", sum);
            Console.WriteLine("Press a key to exit");
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("you chose to use plus");
            int sum1 = x + y;
            Console.WriteLine("result: {0}", sum1);
            Console.WriteLine("Press a key to exit");
            Console.ReadLine();
        }


     }
}

} 正如你所看到的只是使用+如果x i低于y而且 - 如果x大于y。我知道如何使其发挥作用的唯一方式。

5 个答案:

答案 0 :(得分:1)

有各种可能的方法可以完成您的要求。最简单的是要求用户输入操作员进行相应的操作:

以下是相同的代码:

using System.IO;
using System;

class Program
{
    static void Main()
    {
        int x;
        int y;


        Console.WriteLine("Welcome to my calculator program!");
        Console.WriteLine("This calculator for now can only do + and -");

        // Reads x and y from console.
        Console.WriteLine("Enter x :");
        x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter y :");
        y = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Enter operator for corresponding operation on x and y.\nSupported operations x - y and x + y");
        string inputOpr = Console.ReadLine(); // Stores operation to perform

        // Compares input operator to perform operation.
        if (inputOpr == "-"){
            Console.WriteLine("you chose to use minus");
            int result = x - y;
            Console.WriteLine("Result: {0}", result);
            Console.WriteLine("Press a key to exit");
            Console.ReadLine();
        }

        else if (inputOpr == "+"){
            Console.WriteLine("you chose to use plus");
            int result = x + y;
            Console.WriteLine("Result: {0}", result);
            Console.WriteLine("Press a key to exit");
            Console.ReadLine();
        }
        else{
            Console.WriteLine("Invalid Input");
        }
     }
}

答案 1 :(得分:1)

天真的方法(询问用户)已被回答。但你真正想要实现的是编写一个完整的计算器,用户输入一个像2+3这样的字符串,程序只是给出答案。您有志于编写解释器

如果你考虑一下,你将不得不执行三项任务:

  • 扫描用户输入,并将其转换为一系列令牌。这是翻译字符串" 2 + 3"到令牌系列'整数值为2','加上运算符','整数值为3'
  • 解释令牌以计算结果

您对输入的约束越多(例如,正如您所说,只允许+和 - 开始),代码将更简单(如果输入无法根据您设定的规则进行解释,则会失败) )。

如果您想深入挖掘,可以获得有关该主题的众多资源。我喜欢阅读this series of blog posts(作者使用Python,但原则保持不变)。

最后,您会发现您尝试做的很多事情已经实现。有些库已经可以解析和评估数学表达式(示例:NCalcMathos)。

最后,Roslyn允许您轻松解析任何C#表达式,因此它也可用于构建一个简单的计算器,如下所示:

class Program
{
    static void Main(string[] args)
    {
        CSharpReplAsync().Wait();

    }

    private static async Task CSharpReplAsync()
    {
        Console.WriteLine("C# Math REPL");
        Console.WriteLine("You can use any method from System.Math");

        var options = ScriptOptions.Default
            .AddImports("System", "System.Console", "System.Math");

        var state = await CSharpScript.RunAsync("WriteLine(\"Hello from Roslyn\")", options);

        while (true)
        {
            Console.Write("> ");
            string expression = Console.ReadLine();
            if (string.IsNullOrEmpty(expression))
                break;
            try
            {
                state = await state.ContinueWithAsync(expression, options);
                if (state.ReturnValue != null)
                    Console.WriteLine(state.ReturnValue);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

答案 2 :(得分:0)

欢迎来到计算机程序的伟大世界。 应用程序开发就是为用户提供选项并动态处理他/她的请求。 因此,正如您获得x和y的值一样,您可能会从用户那里获得操作符。一个简单的例子是这样的:

int x;
int y;
Console.WriteLine("Welcome to my calculator program!");
Console.WriteLine("This calculator for now can only do + and -");
Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +");

Console.WriteLine("pls write in you x");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("pls write in your y");
y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("insert operator");
string o = Console.ReadLine();

if (o=="-")
{
    Console.WriteLine("you chose to use minus");
    int sum = x - y;
    Console.WriteLine("result: {0}", sum);
    Console.WriteLine("Press a key to exit");
    Console.ReadLine();
}
else if (o=="+")
{
    Console.WriteLine("you chose to use plus");
    int sum1 = x + y;
    Console.WriteLine("result: {0}", sum1);
    Console.WriteLine("Press a key to exit");
    Console.ReadLine();
}
else
{
    Console.WriteLine("the operator is not recognized");
}

如果您觉得有用,请标记答案。

答案 3 :(得分:0)

首先让我感谢您的尝试,现在我会添加一些注释来改进代码段。您可以使用int.TryParse进行转换,这将有助于您处理FormatExceptions,然后从用户处获取操作员并使用切换案例识别它并根据用户输入执行操作。

将此代码视为参考,不要复制和粘贴

int firstNumber, secondNumber;
Console.WriteLine("pls write in you x");
if (!int.TryParse(Console.ReadLine(), out firstNumber))
{
    Console.WriteLine("Sorry this is not an integer, 0 will be assigned");
}
Console.WriteLine("pls write in your y");
if (!int.TryParse(Console.ReadLine(), out secondNumber))
{
    Console.WriteLine("Sorry this is not an integer, 0 will be assigned");
}

/ Now you have two numbers to perform the operation
// You can now prompt the user to enter the operator
Console.WriteLine("pls enter the operator");
char operatorSign = Console.ReadKey().KeyChar;
switch (operatorSign)
{
    case '+' :
        Console.WriteLine("Result {0} + {1} = {2}", firstNumber, secondNumber, firstNumber + secondNumber);
        break;
    case '_':
        Console.WriteLine("Result {0} - {1} = {2}", firstNumber, secondNumber, firstNumber - secondNumber);
        break;
    case '*':
        Console.WriteLine("Result {0} * {1} = {2}", firstNumber, secondNumber, firstNumber * secondNumber);
        break;
    default:             
        Console.WriteLine("Sorry we are not providing this operation");
        break;
}
Console.ReadKey();

答案 4 :(得分:0)

你可以这样做

    static void Main(string[] args)
    {
        int x;
        int y;
        Console.WriteLine("Welcome to my calculator program!");
        Console.WriteLine("This calculator for now can only do + and -");
        Console.WriteLine("If x is highter than y it will do - and if x is lower than y it will do +");

        Console.WriteLine("pls write in you x");
        x = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("pls write in your y");
        y = Convert.ToInt32(Console.ReadLine());

        string opt;
        int res;
        do
        {
            Console.Write("Enter your operator [+/-/:/x]:\t");
            opt= Console.ReadLine();
            res = "/+/-/:/x/".IndexOf("/" + opt + "/");

        } while (res == -1);

        double result;
        switch (opt)
        {
            case "+":
                 result= x + y;
                break;
            case "-":
                result = x - y;
                break;
            case ":":
                result = (double)x/(double)y;
                break;
            case "x":
                result = x*y;
                break;

            default:
                result = -9999;
                break;
        }
        Console.WriteLine("\n{0} {1} {2} = {3}", x, opt, y, result);
        Console.ReadLine();

    }

}