我正在尝试用C#实现堆栈。
问题是Display方法正在打印我添加到堆栈的所有整数的ascii值。 例如。添加到堆栈的3个打印为51,5和53
我甚至尝试过Console.WriteLine(ele.value.GetType()),它将类型返回为System.Int32
using System;
class Program
{
static Stack root, top;
static void Main(string[] args)
{
Console.WriteLine("This is numeric stack.\n1: Push to stack\n2: Pop from stack");
int response = Convert.ToInt16(Console.ReadLine());
if(response == 1)
Push();
}
static void Push()
{
Console.WriteLine("Enter your number...");
int val = Console.Read();
if(root == null)
{
root = new Stack(val);
top = root;
}
else
{
top.top = new Stack(val);
}
Display();
}
static void Display()
{
Stack ele = root;
while (ele != null)
{
int count = 1;
Console.WriteLine(count + ": " + ele.value);
count++;
ele = ele.top;
}
}
}
class Stack
{
public int value;
public Stack top;
public Stack(int val) => this.value = val;
}
答案 0 :(得分:3)
问题的输出不是问题。这是输入。 Console.Read
方法专门返回它读取的字符的Unicode值。如果您要将用户输入的值存储为int
,请致电Console.ReadLine
并通过调用int
将结果转换为Convert.ToInt32
,或者将结果与{{1}合并}}