【问题标题】:c# method overload, with other methodsc#方法重载,配合其他方法
【发布时间】:2016-04-27 18:40:27
【问题描述】:

我需要帮助才能让两者都运行,但当我自己运行时,它们会单独运行。第一个循环生成(但隐藏)20 个随机数,第二个循环添加并显示带有总和的值,但我不知道如何组合。

作业:

您将在 Main 中声明 4 个变量,一个将调用返回随机数的方法的循环,一个将采用整数随机值变量的 void calculate 方法的调用,一个按 ref 平均变量,作为参数的文字值 20 将计算平均值,然后是控制台写入行以显示平均值。接下来是一个循环,该循环将执行 5 次,并提示输入 double 值并将其分配给 double 变量,然后调用 calculate 方法的重载并传递输入的值和 byref 总变量。在重载的计算方法中,您会将传递的值累积到总变量中。循环结束后会显示总数。

输出可能类似于:

20个随机数的平均值是71

输入一个双精度值 10.0

输入一个双精度值 20.0

输入一个双精度值 30.0

输入一个双精度值 40.0

输入一个双精度值 50.1

总计150.1

按任意键继续。

using System;


namespace week7
{
class Program
{
static void Main(string[] args)
{

int randomNumber;//hold random
double average = 0;//hold average
double total = 0;//hold total
double manualEntry = 0; //input entry 

for(int i = 0; i < 20; i++)//20 times
{
randomNumber = getRandom();//by reference

total = total + randomNumber;//by reference
}

calculate(total, ref average, 20);



Console.WriteLine("The average of the 20 random numbers is {0}", average);

total = 0;
Console.WriteLine();//adds space

for (int i = 0; i < 5; i++)
{ 
Console.Write("Enter a double value ");
manualEntry = Convert.ToDouble(Console.ReadLine());
calculate(manualEntry, ref total);



}
Console.WriteLine("The total is {0}",total);

}

static int getRandom()
{
Random randomGenerator = new Random();
return randomGenerator.Next(1,101);
}

//pass the total of the random values, the average variable by reference, and the literal value of 20.


// the entry taken from the console and the variable to hold the total by    reference. 
private static void calculate(double consoleInput, ref double total)
{
total += consoleInput;
}
//pass the total of the random values, the average variable by reference, and   the literal value of 20.
private static void calculate(double total, ref double average, double          denominator)
{
average = total / denominator;
}
}
}

【问题讨论】:

  • 你不应该有两个主要的方法。您应该让它们成为自己的 void 方法,并从一个主函数调用它们。
  • 在将您的问题陈述与您的代码进行比较之后......我认为您的问题太多了,这不是一个好的 SO 问题。首先查看 Main() 流程和问题指示您应该创建的方法。
  • 我建议学习如何设置和使用断点。这将帮助您在学校自行调试,尤其是在没有教授提供帮助的情况下。
  • 静态方法不能被覆盖,Main()绝对不应该有两个实现。
  • 我真的建议你从头开始阅读这本书。不难,很快你就会发现问题。

标签: c# loops methods overloading


【解决方案1】:

您似乎没有遵循非常明确的指示。我忽略了您问题的大部分内容,而是通过向您显示 Calculate() 方法的签名和 Calculate() 方法的重载来尝试让您开始解决标题问题。

Calculate 方法:“一个 void 计算方法,它将采用一个整数随机值变量、一个按 ref 平均变量、一个字面值 20 作为参数”(注意:我不知道你的老师所说的“字面量”是什么意思值 20" 作为参数,所以我使用了默认值)

void Calculate(int randomInteger, ref double average, int literal = 20)
{

}

重载计算方法: “计算方法的重载并传递输入的值和 byref 总变量”

void Calculate(double enteredValue, ref double total)
{

}

【讨论】:

  • 你能告诉我显示 20 个随机数需要添加的位置和内容吗?只是为了检查数学,看看它是否运行正确?
猜你喜欢
  • 2014-05-06
  • 2011-06-19
  • 1970-01-01
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
  • 2016-04-01
相关资源
最近更新 更多