C# 计算器中 getting/printing 个答案的问题

A problem with getting/printing answers in a C# calculator

我正在尝试制作用于学习 C# 的简单项目,并尝试制作一个简单的控制台计算器。我只是在测试 运行 我的程序时到达 getting/printing 答案位时才发现这个当前错误,所以我不知道是否还有其他 errors/things 会或可能不工作或 运行 properly/as 打算。所以如果有任何这些,请告诉我,如果你愿意,你可以自己修复它们。它仅在到达该特定代码行时才识别错误,否则将 运行 程序直到到达错误。

代码:

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;
            }
        }
    }
}

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

answer = num1 + condition + num2;

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

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

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

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

我也给你做一个default case(万一用户的输入不是你期望的,在这种情况下,你可能会要求他重新写一个输入,因为当前输入是无效的) .

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

不能这样做:answer = num1 + condition + 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)
            }

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

if there are any other errors/things that will or may not work"

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

// 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();
  }
}