【问题标题】:Index variable breaking? Looping in C#, Visual Studio 2015索引变量破坏?在 C#、Visual Studio 2015 中循环
【发布时间】:2017-02-23 06:39:47
【问题描述】:

今天,我遇到了一个让我陷入困境的问题。我是一名新手程序员,目前正在学习 C# 的基础知识,在学习 Java 之后。

今天在做一个练习例的时候遇到了这个问题:

Code Running

这是我的代码运行的屏幕截图,我在循环中留下了一个打印语句来显示我的索引变量在做什么。如您所见,每次执行循环时,它都会增加一次以上。在使用 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);
        }

    }
 }

在找出导致此问题的原因之前,我无法真正继续执行此任务。谢谢!

【问题讨论】:

  • 在您的屏幕截图中,值从 0 到 4 以 1 递增。有什么问题?这不是你想要达到的目标吗?

标签: c# loops for-loop indexing


【解决方案1】:

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

【讨论】:

  • 哇,就是这样。谢谢!但为什么这就是解决方案呢?
  • ReadLine() 将让您输入,直到您按 Enter。 Read() 输入一个字符后返回。
  • Read() 也只会在您按 Enter 后返回。但在 int 值流中。
【解决方案2】:

嗨,欢迎来到 C# 的美妙世界

你的问题是Console.Read()

Console.Read() 会给你一个字符 4 的整数,这是你输入的第一个字符。而那个角色将是 52 岁。

所以它会循环 52 次。

Console.ReadLine()代替Console.Read()

【讨论】:

    猜你喜欢
    • 2017-02-24
    • 2016-07-22
    • 2015-12-04
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2016-07-28
    相关资源
    最近更新 更多