0
下面是我的C#作业本周的第5号草案。我首先使用Linq编写了程序,并且它运行良好。不幸的是,方向声明我必须创建自己的方法,而不是使用已经在Linq中找到的美妙Sum()方法。这个源代码的主要问题是方法重载不正确(也可能是我的整个Sum()方法也是错误的)。由于我们全能的文本没有清楚地解释如何重载这样的方法,我有点失落......(或者很多失败)。错误CS1501:我没有正确地重载Sum()方法
这里是赋值指令(再一次):
“创建接受任意数量的整数参数,并显示它们的总和)命名的总和(方法写演示和的Main()方法()方法当传递一个,三个,五个或十个整数的数组时,它会正常工作。将该程序保存为UsingSum.cs。“
从微软的Visual C#®2008年,介绍了面向对象程序设计,3E,乔伊斯·法雷尔
这里是我的源代码:
using System;
public class UsingSum
{
public static void Main()
{
//Step 1: Adding 1, 3 and 5
int[] array1 = { 1, 3, 5 };
int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int j;
int firstSum;
int secondSum;
Console.Write("When the numbers 1, 3 and 5 are added together, using the Sum() method, the answer is: ");
firstSum = Sum(array1);
Console.WriteLine("{0}", firstSum);
//Step 2: Entering variables into Array2[10]
Console.Write("Enter first integer for addition: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter second integer for addition: ");
b = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter third integer for addition: ");
c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter forth integer for addition: ");
d = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter fifth integer for addition: ");
e = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter sixth integer for addition: ");
f = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter seventh integer for addition: ");
g = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter eighth integer for addition: ");
h = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter ninth integer for addition: ");
i = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter tenth integer for addition: ");
j = Convert.ToInt32(Console.ReadLine());
int[] array2 = { a, b, c, d, e, f, g, h, i, j };
Console.Write("The total of {0} + {1} + {2} + {3} + {4} + {5} + {6} + {7} + {8} + {9} is: ",
a, b, c, d, e, f, g, h, i, j);
secondSum = Sum(array2);
Console.WriteLine("{0}", secondSum);
}
//Step 3: Defining the Sum() method
public static int Sum(int a, int b)
//My overload is generating error CS1501: No overload for method 'Sum' takes '1' arguments
{
int sum = 0;
int[] adder = new int[0];
//designating an array with no parameters...
for(int a = 0; a < adder.Length; ++a)
adder[a] = a;
foreach(int b in adder)
sum += b;
Console.WriteLine(" " + sum);
}
}
好吧,我给一个尝试:-)谢谢你这么清楚解释问题。 – Nooob 2010-10-24 17:33:54
它的工作! :-)我忘了在最后加上回报。实际的Sum函数对任何事物都产生0,但我会想出来......谢谢你的帮助。 – Nooob 2010-10-24 17:37:57
...我的源代码编译和工作完美。它生成0是因为我在foreach中引用了加法器数组(而在加法器中是int b)而不是引用用于重载Sum()方法的“输入”数组。非常感谢所有帮助我在本周末推出这些东西的人们。 :-) – Nooob 2010-10-24 18:04:12