题解 | #简单计算器#

简单计算器

https://www.nowcoder.com/practice/b8f770674ba7468bb0a0efcc2aa3a239

public class Program {
    public static void Main() {
        string line = System.Console.ReadLine();

        if (line.Contains("+") || line.Contains("-") || line.Contains("*") ||
                line.Contains("/")) {
            //如果是加法
            if (line.Contains("+")) {
                string[] lines = line.Split("+");
                double left = double.Parse(lines[0]);
                double right = double.Parse(lines[1]);
                double result = left + right;
                System.Console.WriteLine(left.ToString("F4") + "+" + right.ToString("F4") + "="
                                         + result.ToString("F4"));
            }
            //如果是减法
            else if (line.Contains("-")) {
                string[] lines = line.Split("-");
                double left = double.Parse(lines[0]);
                double right = double.Parse(lines[1]);
                double result = left - right;
                System.Console.WriteLine(left.ToString("F4") + "-" + right.ToString("F4") + "="
                                         + result.ToString("F4"));
            }
            //如果是乘法
            else if (line.Contains("*")) {
                string[] lines = line.Split("*");
                double left = double.Parse(lines[0]);
                double right = double.Parse(lines[1]);
                double result = left * right;
                System.Console.WriteLine(left.ToString("F4") + "*" + right.ToString("F4") + "="
                                         + result.ToString("F4"));
            }
            //如果是除法
            else if (line.Contains("/")) {
                string[] lines = line.Split("/");
                double left = double.Parse(lines[0]);
                double right = double.Parse(lines[1]);
                double result = left / right;
                if (right != 0.0)
                    System.Console.WriteLine(left.ToString("F4") + "/" + right.ToString("F4") + "="
                                             + result.ToString("F4"));
                else
                    System.Console.WriteLine("Wrong!Division by zero!");

            }

        } else
            System.Console.WriteLine("Invalid operation!");
    }
}

全部评论

相关推荐

头像
昨天 15:46
已编辑
中南大学 后端
字节国际 电商后端 24k-35k
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务