C# Trip类方法工作不正常
我必须制作一个旅行类,该类需要用户输入目的地、旅行距离、汽油成本和使用的加仑数,并输出每加仑英里数和每英里成本 由于某些原因,我的mpg和cpm总是输出0,我做错了什么 课程类别:C# Trip类方法工作不正常,c#,methods,C#,Methods,我必须制作一个旅行类,该类需要用户输入目的地、旅行距离、汽油成本和使用的加仑数,并输出每加仑英里数和每英里成本 由于某些原因,我的mpg和cpm总是输出0,我做错了什么 课程类别: class Program { static void Main(string[] args) { Trip t1 = new Trip("Columbus, OH", 150, 2.95, 5); Trip t2 = new Trip("Edmonton, AB",
class Program
{
static void Main(string[] args)
{
Trip t1 = new Trip("Columbus, OH", 150, 2.95, 5);
Trip t2 = new Trip("Edmonton, AB", 3300, 2.75, 50);
Trip t3 = new Trip("Calgary, AB", 3100, 2.50, 45);
Console.WriteLine(t1);
Console.WriteLine(t2);
Console.WriteLine(t3);
}
}
旅行班
class Trip
{
//class variables
string destination;
int distance;
double costOfGas;
int gallons;
int mpg;
double cpm;
//constructors
public Trip()
{
destination = "n.a.";
distance = 1;
costOfGas = 1;
gallons = 1;
}
public Trip(string destinationValue, int distanceValue,
double costOfGasValue, int gallonsValue)
{
Destination = destinationValue;
Distance = distanceValue;
CostOfGas = costOfGasValue;
Gallons = gallonsValue;
}
//properties
public string Destination
{
get { return destination; }
set { destination = value; }
}
public int Distance
{
get { return distance; }
set { distance = value; }
}
public double CostOfGas
{
get { return costOfGas; }
set { costOfGas = value; }
}
public int Gallons
{
get { return gallons; }
set { gallons = value; }
}
public int MPG
{
get { return mpg; }
set { mpg = MilesPerGallon(value); }
}
public double CPM
{
get { return cpm; }
set { cpm = CostPerMile(value); }
}
//user-defined methods
public int MilesPerGallon(int value)
{
return distance / gallons;
}
public double CostPerMile(double value)
{
return costOfGas * mpg;
}
override
public string ToString()
{
return "Trip["
+ destination + ", "
+ distance + ", "
+ costOfGas + ", "
+ gallons + "]"
+ "\n Miles Per Gallon = " + mpg
+ ", Cost Per Mile = " + cpm;
}
}
输出:
特里普[哥伦布,俄亥俄州,150,2.95,5]
每加仑英里数=0,每英里成本=0
等等。您使用的是
mpg
和cpm
,这些值从未设置过。你使用的MPG
和CPM
也很奇怪。您实际上不需要MPG
和CPM
属性,将MilesPerGallon
和CostPerMile
方法更新为只计算值的属性:
public int MilesPerGallon { get { return distance / gallons; } }
public double CostPerMile { get { return costOfGas * MilesPerGallon; } }
override
public string ToString()
{
return "Trip["
+ destination + ", "
+ distance + ", "
+ costOfGas + ", "
+ gallons + "]"
+ "\n Miles Per Gallon = " + MilesPerGallon
+ ", Cost Per Mile = " + CostPerMile;
}
MPG
和CPM
(MPG
和CPM
)的支持字段仅在这些属性的设置器中设置。因为你从不打电话给二传手,他们就永远不会被设定
相反,您应该计算属性中的值,而不使用setter
public int MPG
{
get { return distance / gallons; }
}
public double CPM
{
get { return costOfGas * MPG; }
}
并删除支持字段,改为使用属性。对于类来说,允许设置
MPG
和CPM
属性是没有意义的。因为您从未在代码中调用CPM或CMP属性,所以MPG和CMP字段从未更改,所以它们总是0。您的代码没有意义。你试过调试它吗?你应该对其中的大多数使用自动属性,不需要备份字段。此fiddle具有修复功能。它们作为属性更具意义,因为在这些函数中未使用且不需要value
参数。也许还可以删除value args?是的,只是错过了将其更改为使用属性。谢谢。我以前做过,但是我用mpg,cpm代替了mpg和cpm,所以结果还是一样的。我忽略了一个简单的错误。