簡體   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