简体   繁体   English

C# 将数字相加的计算器

[英]C# calculator that adds numbers together

I want to add two strings together like a calculator, not next to each other.我想像计算器一样将两个字符串加在一起,而不是彼此相邻。 This is my code:这是我的代码:

        void MainAdd()
        {
            Console.WriteLine("");
            string Add1 = Console.ReadLine();
            Console.WriteLine("");
            string Add2 = Console.ReadLine();
            string add = Add1 + Add2;
            Console.WriteLine(add);
            startcode();
        }

How can I make it work like a calculator?我怎样才能让它像计算器一样工作?

static void Main(string[] args)
{
    double add1 = InputValue("Input first addend");
    double add2 = InputValue("Input second addend");

    double sum = add1 + add2;
    Console.WriteLine("Sum: " + sum);
}

static double InputValue(string message)
{
    double value;
    string input;

    do
    {
        Console.WriteLine(message);
        input = Console.ReadLine();
    }
    while (!double.TryParse(input, out value));

    return value;
}

Please read about built in types , you can't do numerical operations on string (text):请阅读有关内置类型的信息,您不能对string (文本)进行数值运算

int Add1 = int.Parse(Console.ReadLine());
int Add2 = int.Parse(Console.ReadLine());
int add = Add1 + Add2;
Console.WriteLine(add);

Also, this was just an example, you should never trust the user to enter the right thing, Use TryParse .此外,这只是一个示例,您永远不应该相信用户输入正确的内容,使用TryParse

int add = Int32.Parse(Add1) + Int32.Parse(Add2);
Console.WriteLine(add);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM