我需要帮助使用在一个类在一个不同的类中制作的数组,并得到它的总和
本文关键字:一个 数组 帮助 | 更新日期: 2023-09-27 18:18:52
在我的输入类中,我有一个名为score的数组。我需要在我的MathFun类中使用它并获得它的总和。
class Inputs
{
int amountgames;
public void AmountOfGames()
{
Console.WriteLine("How many games did you play?");
amountgames = int.Parse(Console.ReadLine());
}
public void Scores()
{
int[] score = new int[amountgames];
Console.WriteLine("score for game ");
for (int i = 0; i < score.Length; i++)
{
score[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("'nThe scores you entered are");
for (int j = 0; j < score.Length; j++)
{
Console.WriteLine(score[j]);
}
}
}
class MathFun
{
int number1;
int number2;
int total;
int averaged;
public int Average;
public int Added1;
public MathFun()
{
}
public void DivideThem()
{
Average = number1 / number2;
}
public void Added()
{
Added1 = inputs.score.sum();
//This is where in the array and its sum
}
public MathFun(int innumber1, int innumber2)
{
number1 = innumber1;
number2 = innumber2;
}
public int Number1
{
get
{
return number1;
}
set
{
number1 = value;
}
}
public int Number2
{
get
{
return number2;
}
set
{
number2 = value;
}
}
public int Total
{
get
{
return total;
}
}
public int Averaged
{
get
{
return averaged;
}
}
public void CalcTotal()
{
total = Added1;
averaged = Average;
}
}
你有两个选择
- 创建一个可以在MathFun中使用的Inputs的实例。
- 将Scores()设置为静态,这样就不需要实例了。如果你这样做,amountgames和AmountOfGames()也必须变成静态。
-
无论哪种方式,您都必须返回Scores()的输入,或者以某种方式将它们存储在类中。
public int[] Scores(){Int [] score = new Int [amountgames];
Console.WriteLine("score for game "); for (int i = 0; i < score.Length; i++) { score[i] = int.Parse(Console.ReadLine()); } Console.WriteLine("'nThe scores you entered are"); for (int j = 0; j < score.Length; j++) { Console.WriteLine(score[j]); } } return score;
}
下面是你如何使用第一种方法
Inputs inputs = new Inputs();
int[] scores = Scores();
// Use scores with MathFun
注意:我通常不会创建一个既负责向控制台写入分数又负责返回分数的函数。最好为每个方法指定一个职责。这里的解决方案是尽可能少地修改当前代码。
找到自己的解决方案
int sum = 0;
for (int i = 0; i < score.Length; i++)
{
sum += score[i];
}
将其添加到数组中以将其全部加起来然后创建一个sum