繁体   English   中英

C# 中用户对数组的输入并在控制台中显示

[英]Input from user to array and Display in Console in C#

我是 C# 的初学者,我想知道这段代码出了什么问题。

  1. 我希望用户输入数字的数量
  2. 然后创建一个具有该数量的数组
  3. 最后我想显示数组中的所有数字。

代码:

using System;
using System.Threading;
using System.Collections.Generic;

namespace Console_Project_alpha
{
    
class Program 
{
    
    static void Main(string[] args)
    {
            Console.Write("Enter the amount of numbers: ");
            int amount = Convert.ToInt32(Console.ReadLine());
            
            int[] numbers = new int[amount];
            string nth = "";

            
            
            for( int i = 1; i <= amount ; i++)
            {
                        if(i == 1)
                        {
                            nth = i + "st";    
                        }
                        else if( i == 2)
                        {
                           nth = i + "nd";
                        }
                        else if( i == 3)
                        {
                            nth = i + "rd";   
                        }else{
                            nth = i + "th";
                        }
                
                Console.Write("\nEnter " + nth + " Number:");
                int num = Convert.ToInt32(Console.ReadLine());
               
               for(int j = 0; j <= numbers.Length; j++)
                {
                    numbers[j] = num;
                    
                }
                
            }
            System.Console.WriteLine(numbers);

            

    }

   }
}

非常感谢任何帮助。 提前致谢

  1. 在您的代码中,您总是将相同的值覆盖到数组中的所有索引。
  2. 如果你想在控制台中显示数组中的值,只需在数组之后迭代

根据您的代码正确工作的示例:

class Program
{

    static void Main(string[] args)
    {
        Console.Write("Enter the amount of numbers: ");
        int amount = Convert.ToInt32(Console.ReadLine());

        int[] numbers = new int[amount];
        string nth = "";
        int index = 0;

        for (int i = 1; i <= amount; i++)
        {
            if (i == 1)
            {
                nth = i + "st";
            }
            else if (i == 2)
            {
                nth = i + "nd";
            }
            else if (i == 3)
            {
                nth = i + "rd";
            }
            else
            {
                nth = i + "th";
            }

            Console.Write("\nEnter " + nth + " Number:");
            int num = Convert.ToInt32(Console.ReadLine());

            numbers[index] = num;
            index++;
        }

        for (int i = 0; i <= numbers.Length - 1; i++)
        {
            Console.WriteLine(numbers[i]);
        }

        Console.ReadLine();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM