c# - 从用户输入到数组并在 C# 中的控制台中显示
问题描述
我是 C# 的初学者,我想知道这段代码有什么问题。
- 我希望用户输入数字的数量
- 然后创建一个具有该数量的数组
- 最后我想显示数组中的所有数字。
编码:
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);
}
}
}
非常感谢任何帮助。提前致谢
解决方案
- 在您的代码中,您总是将相同的值覆盖到数组中的所有索引。
- 如果要在控制台中显示数组中的值,只需在数组之后迭代
根据您的代码正确工作的示例:
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();
}
}
推荐阅读
- jquery - 如何使自定义属性仅适用于一个元素?
- reactjs - 如何将数据馈送推送到仪表板以便能够在 react-admin 中创建图表?
- c# - 点击时更改 ListView 项目的 RowDefinition
- markdown - 降价命名链接的第一个等价物是什么?
- function - 我的功能将关闭或启动多个虚拟机
- python - 与“in”关键字连接会产生错误的结果
- html - 如何在 WordPress 中实现自定义标头的引导小部件代码?
- google-colaboratory - 如何在 Google Colab 中卸载驱动器并重新安装到另一个驱动器?
- css - 我如何解决悬停问题?
- jquery - Jquery .click 事件未触发