我正在创建一个友好的人工智能,其名字是菲尔;),但我需要它能够做数学。我确实尝试过,也尝试过+=,但它不起作用。例如,如果我执行 1+1,而不是 2,则结果为 11。这是我的代码:
namespace Game
{
public static class Program
{
//commands
public static string enteredCommand;
public static string commanddomath = "doMath";
//Math command stuff
public static string MathOperation;
public static string FirstOperatorNumber;
public static string SecondOperatorNumber;
public static string FinalAwnser;
static void Main()
{
if (enteredCommand == "doMath")
{
Console.WriteLine("Ok");
Console.WriteLine("What Operation should I do?");
MathOperation = Console.ReadLine();
if (MathOperation == "+")
{
Console.WriteLine("Addition! Easy! What is the first number? ex. 6");
FirstOperatorNumber = Console.ReadLine();
Console.WriteLine("Ok, what do you want the second number to be? ex. 8");
SecondOperatorNumber = Console.ReadLine();
FinalAwnser = FirstOperatorNumber + SecondOperatorNumber;
Console.WriteLine("Ok! The awnser is..." + FinalAwnser);
}
}
else
{
Console.WriteLine("That is not a command");
}
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏!谢谢
您将用户的输入 (FirstOperatorNumber
和SecondOperatorNumber
) 存储为字符串。加法运算符 ( ) 当应用于两个字符串时,会执行称为串联的+
操作:它将每个字符串中的字符相加以形成另一个字符串。
但您需要加法,这是对两个整数使用加法运算符的结果。因此,您必须通过在变量声明中将“string”替换为“int”来将用户的输入存储为整数:
public static int FirstOperatorNumber;
public static int SecondOperatorNumber;
Run Code Online (Sandbox Code Playgroud)
输入仍然是一个字符串,因此您还需要对其进行转换,如下所示:
FirstOperatorNumber = Int32.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)