[英]Index variable breaking? Looping in C#, Visual Studio 2015
今天,我遇到了一个困扰我的问题。 我是一名新手程序员,在学习Java之后,目前正在学习C#的基础知识。
今天,当我遇到此问题时,我正在研究一个练习示例:
这是我的代码运行的屏幕截图,我在循环内保留了一条print语句,向我展示我的索引变量在做什么。 如您所见,每次循环执行,它递增的次数不止一次。 使用while循环和其他项目时,我也得到了相同的结果。
这是代码:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many values are you entering");
int value = Convert.ToInt32(Console.Read());
Console.WriteLine("Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.Read());
Console.WriteLine("i is: "+i);
}
}
}
在确定导致此问题的原因之前,我无法真正进行此分配。 谢谢!
尝试使用ReadLine()
代替Read()
Console.WriteLine("How many values are you entering");
string input = Console.ReadLine();
int value = Convert.ToInt32(input);
Console.WriteLine(value +" Please enter the values of the currencies you are converting.");
decimal[] money = new decimal[value];
for (int i = 0; i < money.Length; i++)
{
money[i] = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("i is: " + i);
}
嗨,欢迎来到C#的美好世界
您的问题是Console.Read()
Console.Read()
将为您提供字符4
的整数,这是您第一个键入的字符。 这个字符将是52。
因此它将循环52次。
代替Console.Read()
使用Console.ReadLine()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.