C# 方法运行两次,而它应该只运行一次 class-Myclass { 公共字符串驱动器1() { 字符串a=“”; 控制台。写入(“请输入驱动程序名称:”); a=Console.ReadLine(); 返回a; } 公共int numberOfTrips() { int a=0; { 控制台。写入(“输入行程数:”); a=Convert.ToInt32(Console.ReadLine()); } 返回a; } 公开名单付款() { 列表a=新列表(); 浮点输入; 对于(int i=0;i
而不是在Main()和Payments()中调用numberOfTrips())您可以尝试在MyClass中创建一个实例变量或静态变量。然后,在计算完所有付款后,您可以从该变量中获取行程数。这是正确的。它第一次运行主要是设置“trip”变量。第二次运行是在付款中,在for循环声明内。只需传递从C# 方法运行两次,而它应该只运行一次 class-Myclass { 公共字符串驱动器1() { 字符串a=“”; 控制台。写入(“请输入驱动程序名称:”); a=Console.ReadLine(); 返回a; } 公共int numberOfTrips() { int a=0; { 控制台。写入(“输入行程数:”); a=Convert.ToInt32(Console.ReadLine()); } 返回a; } 公开名单付款() { 列表a=新列表(); 浮点输入; 对于(int i=0;i,c#,C#,而不是在Main()和Payments()中调用numberOfTrips())您可以尝试在MyClass中创建一个实例变量或静态变量。然后,在计算完所有付款后,您可以从该变量中获取行程数。这是正确的。它第一次运行主要是设置“trip”变量。第二次运行是在付款中,在for循环声明内。只需传递从numberOfTrips作为参数到付款的编号: class Myclass { public string Driver1() { string a = "";
numberOfTrips
作为参数到付款的编号
:
class Myclass
{
public string Driver1()
{
string a = "";
Console.Write("Please enter drivers name: ");
a = Console.ReadLine();
return a;
}
public int numberOfTrips()
{
int a = 0;
{
Console.Write("Enter the number of trips: ");
a = Convert.ToInt32(Console.ReadLine());
}
return a;
}
public List<float> Payments()
{
List<float> a = new List<float>();
float input;
for (int i = 0; i<numberOfTrips(); i++)
{
Console.Write("Enter payment {0}: ", (1 + i));
input = float.Parse(Console.ReadLine());
Console.WriteLine("Payment added");
a.Add(input);
}
return a;
}
}
class Program
{
static void Main(string[] args)
{
Myclass a = new Myclass();
string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments().Sum();
Console.WriteLine("\nDriver: {0}\n" + "Number of trips: {1}\n" + "Total payment: {2}\n", name, trip, total);
}
}
我刚刚尝试过这个,它很有效,谢谢:)我对这个C#很新,只学了几天,所以你能告诉我(int tripcount)是做什么的,以及numberOfTrips是如何传递到tripcount的吗。另外,为什么我必须在这里使用(trip):float total=a.Payments(trip).Sum();@CharlieWalkden您从第一次调用
numberOfTrips
时获取变量,并将其存储到变量trip
中。然后您将变量作为参数传递给Payments
,这基本上使该方法能够访问该变量,以便可以使用它。(要获得更深入的解释,请查阅有关方法和参数的教程。)谢谢,我非常感谢:)
public List<float> Payments(int tripCount)
{
List<float> a = new List<float>();
float input;
for (int i = 0; i < tripCount; i++)
{
Console.Write("Enter payment {0}: ", (1 + i));
input = float.Parse(Console.ReadLine());
Console.WriteLine("Payment added");
a.Add(input);
}
return a;
}
Myclass a = new Myclass();
string name = a.Driver1();
int trip = a.numberOfTrips();
float total = a.Payments(trip).Sum();