问题描述
我得到了一个课堂作业,他们希望我们制作一个 10 的数组,并有一个带有多个提示的菜单,例如更改数组的编号、获取数组的总和等。他们想要每个菜单选项拥有自己的方法,并具有以下变化:
public void enterNum(int[] args)
当需要将 5 个方法设置为 void 时,我在理解如何在 5 个方法之间存储数组时遇到问题,并且我不确定在将信息发送到方法时如何格式化。我已经构建了一个草稿作为 switch 语句
using System;
namespace Lab
{
class Program
{
static void Main(string[] args)
{
int input,x,y,sum = 0;
int[] initArray = new int[10];
do
{
Console.Write("Would you like to: \n1) Enter a number\n2)Print the array \n3)find the sum of the array\n4)Reset the array\n5)Quit\n");
input = Convert.ToInt32(Console.ReadLine());
switch (input)
{
case 1:
Console.Write("Enter the slot: ");
x = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the new value: ");
y = Convert.ToInt32(Console.ReadLine());
initArray[x] = y;
break;
case 2:
for (int a = 0; a < 10; a++)
{
Console.Write(" | " + initArray[a]);
}
Console.Write("\n");
break;
case 3:
for (int b = 0; b < 10; b++)
{
sum += initArray[b];
}
sum /= 10;
Console.WriteLine(sum);
sum = 0;
break;
case 4:
for (int c = 0; c < 10; c++)
{
initArray[c] = 0;
}
break;
}
} while (input != 5);
}
}
}
我遇到问题的一个例子是
public static void Main(string[] args)
{
int[] NewArr = new int[10];
enterNum(NewArr);
//trying to change number of array
printSum(NewArr);
//getting sum from array established in Main
}
public void enterNum(int[] args)
{
Console.Write("Enter the slot: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the new value: ");
int y = Convert.ToInt32(Console.ReadLine());
NewArr[x] = y;
return;
}
public void printSum(int[] args)
{
for (int b = 0; b < 10; b++)
{
sum += NewArr[b];
}
sum /= 10;
Console.WriteLine(sum);
return;
}
解决方法
试试
using System;
namespace ConsoleApp7
{
class Program
{
public static void Main(string[] args)
{
int[] NewArr = new int[10];
enterNum(ref NewArr);
//trying to change number of array
printSum(NewArr);
//getting sum from array established in Main
}
public static void enterNum(ref int[] args)
{
Console.Write("Enter the slot: ");
int x = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the new value: ");
int y = Convert.ToInt32(Console.ReadLine());
args[x] = y;
return;
}
public static void printSum(int[] args)
{
int sum = 0;
for (int b = 0; b < 10; b++)
{
sum += args[b];
}
sum /= 10;
Console.WriteLine(sum);
return;
}
}
}
还有一行:
sum /= 10;
将计算平均值,而不是总和。