【问题标题】:A problem with getting/printing answers in a C# calculator在 C# 计算器中获取/打印答案的问题
【发布时间】:2023-04-09 08:52:01
【问题描述】:

我正在尝试制作用于学习 C# 的简单项目,并尝试制作一个简单的控制台计算器。在测试运行我的程序时,我只在获取/打印答案位时发现了这个当前错误,所以我不知道是否有任何其他错误/事情会或可能不会正常工作或按预期运行。因此,如果有任何这些,请告诉我,如果您愿意,您可以自己修复它们。它仅在到达特定代码行时才识别错误,否则将运行程序直到到达错误为止。

代码:

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

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            string num1;
            string num2;
            string condition;
            string answer;
            Console.WriteLine("Calculator");
            Console.WriteLine("For division, use /. For multiplication, use *.\n");
            
            while (true)
            {
                Console.WriteLine("Enter a number: "); // gets first number to add in problem
                num1 = Console.ReadLine();
                Console.WriteLine("Enter a condition: "); // gets condition to add in problem
                condition = Console.ReadLine();
                Console.WriteLine("Enter your second number: "); // gets second number to add in problem
                num2 = Console.ReadLine();
                Console.WriteLine("Calculating..");
                // converting strings to int and working out answer
                Convert.ToInt32(num1);
                Convert.ToInt32(num2);
                // error is from here on (not sure if the Convert.ToInt32() code above causes errors)
                answer = num1 + condition + num2;
                Convert.ToInt32(answer);
                Console.WriteLine(answer);
                // sets values to null after getting & printing answer (probably unnessessary)
                answer = null;
                num1 = null;
                num2 = null;
                condition = null;
            }
        }
    }
}

【问题讨论】:

  • @Misha Zaslavsky 你也是!

标签: c# error-handling calculator


【解决方案1】:

当遇到这样的问题时 - 例程太复杂无法测试:

如果有任何其他错误/事情会或可能不会起作用”

将例程拆分为更小的例程:开始提取方法

// Get integer value from user
public static int ReadInteger(string title) {
  while (true) {
    if (!string.IsNullOrEmpty(title))
      Console.WriteLine(title);

    if (int.TryParse(Console.ReadLine(), out int result))
      return result;

    Console.WriteLine("Sorry, not a valid integer value, please, try again.");
  }
}

// Get character operator ('+', '-' etc.) from user
public static char ReadOperator(string title, string operators) {
  while (true) {
    if (!string.IsNullOrEmpty(title))
      Console.WriteLine(title);

    string input = Console.ReadLine().Trim();

    if (input.Length == 1 && operators.Contains(input[0]))
      return input[0];  

    Console.WriteLine("Sorry, not a valid operator, please, try again.");
  }
}

现在我们准备实现Main 方法:

static void Main(string[] args) {
  while (true) {
    int num1 = ReadInteger("Enter a number: ");
    char op = ReadOperator("Enter a condition: ", "+-*/");
    int num2 = ReadInteger("Enter your second number: ");

    //TODO: I've skipped error handling (zero division, overflow)
    int answer = 
      op == '+' ? num1 + num2 :
      op == '-' ? num1 - num2 : 
      op == '*' ? num1 * num2 :
      op == '/' ? num1 / num2 : 0;

    Console.WriteLine($"{num1} {op} {num2} = {answer}");
 
    //TODO: it's a right place here to ask user if (s)he wants to continue
    Console.WriteLine();
  }
}

【讨论】:

    【解决方案2】:

    您以字符串形式接收输入(条件)

    不能这样做:答案 = num1 + 条件 + num2 因为这些变量是 字符串

    您必须使用 switch 进行检查,例如:

                int num1 = 0, num2 = 0, answer = 0;
                string condition;
                Console.WriteLine("Calculator");
                Console.WriteLine("For division, use /. For multiplication, use *.\n");
    
                while (true)
                {
                    Console.WriteLine("Enter a number: "); // gets first number to add in problem
                    num1 = int.Parse(Console.ReadLine());
                    Console.WriteLine("Enter a condition: "); // gets condition to add in problem
                    condition = Console.ReadLine();
                    Console.WriteLine("Enter your second number: "); // gets second number to add in problem
                    num2 = int.Parse(Console.ReadLine());
                    Console.WriteLine("Calculating..");
                    // converting strings to int and working out answer
                    Convert.ToInt32(num1);
                    Convert.ToInt32(num2);
                    // error is from here on (not sure if the Convert.ToInt32() code above causes errors)
                    switch (condition)
                    {
                        case "/":
                            answer = num1 / num2;
                            break;
                        case "*":
                            answer = num1 * num2;
                            break;
                        case "+":
                            answer = num1 + num2;
                            break;
                        case "-":
                            answer = num1 - num2;
                            break;
                        default:
                            Console.WriteLine("error : unknown operator");
                            break;
                    }
                    Console.WriteLine(answer);
                    // sets values to null after getting & printing answer (probably unnessessary)
                }
    

    【讨论】:

    • 我将 num1 和 .. 从 string 更改为 int ,并在读取输入时通过 int.Parse 将它们转换为 int
    【解决方案3】:

    您不能这样做,因为所有变量都是 strings 而不是实际值(例如:num1 & num2 应该是 ints/doubles... 并且条件应该是一个真正的运算符)。

    answer = num1 + condition + num2;
    

    另外,你不能这样做,因为假设用户输入了乘号,然后"*"的字符串不等于*的符号。

    相反,您可以执行一些switch-case 语句来检查condition 变量的值。此外,您需要确保 num1 & num2 是数字(您可以将它们解析/尝试解析为数字 (int/double...))。您还必须将它们解析为另一个变量,因为它们是字符串。

    switch (condition)
    {
        case '*':
            answer = numX * numY;
            break;
        case "/":
           // Validate that numY is not 0 to avoid [DivideByZeroException][1]
           answer = numX / numY;
           break;
        ...
    }
    

    注意,这只是一种方法,我只是给你一个小例子,可能会帮助你继续。

    我还建议你做一个默认情况(如果用户的输入不是你所期望的,在这种情况下,你可以再次要求他写一个输入,因为当前输入是无效的)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多