C# 为什么2会自动转换为299?
我是新来的:C# 为什么2会自动转换为299?,c#,windows,C#,Windows,我是新来的: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { private static void Main() { Console.WriteLine("Welcome to my calculator
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
private static void Main()
{
Console.WriteLine("Welcome to my calculator");
Console.WriteLine("Calculator only supports -,+,/,*");
Console.WriteLine("Calculator V1.20 alpha");
Console.WriteLine("Enter your first number");
int num1 = Console.ReadKey().KeyChar;
Console.WriteLine("Enter your operator");
Console.WriteLine();
char operation = Console.ReadKey().KeyChar;
Console.WriteLine("Enter your second number");
Console.WriteLine();
int num2 = Console.ReadKey().KeyChar;
//the answer variables
int answersubtract = num1 - num2;
int answeradd = num1 + num2;
int answermulti = num1 * num2;
int answerdiv = num1 / num2;
if (operation == '-')
{
Console.WriteLine(answersubtract);
}
else if (operation == '+')
{
Console.WriteLine(answeradd);
}
else
{
if (operation == '*')
{
Console.WriteLine(answermulti);
}
else
{
if (operation == '/')
{
Console.WriteLine(answerdiv);
}
}
}
Console.ReadKey();
}
}
}
编辑:
我向程序发送的输入是:
1+2
因为当您输入
2
时,其表示为char
,其值为229
int num1 = Console.ReadKey().KeyChar;
你在读一个字符,而不是一个数字。查看ConsoleKeyInfo.KeyChar的文档
允许用户输入实数:
int num1 = int.Parse(Console.ReadLine());
请关注程序版本2中的错误处理和switch语句。您能告诉我们您遇到了什么问题吗?“当我做a的时候,b发生了,但我想要c”你能说得更具体一点吗?在什么情况下,
2
会被转换成299
?除了'2'
的ASCII值是0x32
或十进制50之外。@John:这个答案确实确定了一个合法的问题,我认为它不值得投反对票。@John:使用编码的整数值而不是它所代表的数字是代码的一个合理问题,应该予以修正。然后,不正确的值经过一些计算得到229,它不是一个具有该值的字符,但这个问题几乎肯定会导致不正确的结果。@John,Ben:问题是缺少复制步骤。我们不知道它遵循哪条代码路径来获得该结果。另外,这里正在进行一些严肃的电话游戏,因为标题是299
,而不是229
。@Ben:编译后发现比这简单得多。他输入的字符是:“1+2”。最后一行是他输入的2
并在其后面附加99
,因此299
@John-我不会用一根十英尺长的杆子去碰它。不管怎么说,299在哪里起作用(不是229)?