我正在尝试完成一个C#家庭作业练习,其中我要求输入以升为单位的天然气成本和加仑成本。然后比较价格,发现哪个实际上是更便宜的价格。我可以得到我的代码来比较价格,然后返回最低的值,但似乎无法弄清楚如何将该值转换回字符串,这是电台的名称。 我是编程的新手,所以我很难过。 以下是我的代码:
//Programmer: Michael Davis
//Date: 10/22/14
//Purpose of program: To receive input regarding gas prices in liters and input in gallons, then compare prices to determine which is truly less expensive.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GasPriceComparison
{
class Program
{
static void Main(string[] args)
{
string input1;
string input2;
char CanadianFuel;
char AmericanFuel;
double value1;
double value2;
double cheap;
Console.WriteLine("How much is gas per litre at CanadianFuel?");
input1 = Console.ReadLine( );
Console.WriteLine("How much is gas per gallon at AmericanFuel?");
input2 = Console.ReadLine( );
value1 = double.Parse(input1);
value2 = double.Parse(input2) * .264172;
if (value1 > value2)
{
cheap = value2.ToChar[12](AmericanFuel);
}
else
{
cheap = value1.ToChar[12](CanadianFuel);
}
Console.WriteLine(("The cheaper gas is: ") + cheap);
Console.ReadLine();
}
}
}
答案 0 :(得分:4)
简单的答案是在ToString()
上调用cheap
方法,如下所示:
if (value1 > value2)
{
cheap = value2;
}
else
{
cheap = value1;
}
Console.WriteLine(("The cheaper gas is: ") + cheap.ToString());
但是,这可能无法完全按照您想要的方式显示。所以你需要格式化它。你可以写:
cheap.ToString("N2")
将格式化为两位小数。您还可以将格式字符串传递给Console.WriteLine
,如下所示:
Console.WriteLine("The cheaper gas is: {0:N2}", cheap);
答案 1 :(得分:2)
您缺少的是您接受用户的值与这些值的名称或含义之间的关系。要以OO方式执行此操作,您可以为您的燃料类型定义一个类
public class FuelRegion
{
public string Name { get; set; }
public double CostPerLitre { get; set; }
public FuelRegion(string name)
{
this.Name = name;
}
}
然后在你的Main方法中实例化一个用于American Fuel,一个用于Canadian Fuel并声明一个用于最便宜的:
FuelRegion americanFuel = new FuelRegion("American Fuel");
FuelRegion canadianFuel = new FuelRegion("Canadian Fuel");
FuelRegion cheapestFuel;
现在,在解析值时,不要将它们写入value1和value2,请将它们写入americanFuel.CostPerLitre和candadianFuel.CostPerLitre
candadianFuel.CostPerLitre = double.Parse(input1);
americanFuel.CostPerLitre = double.Parse(input2) * .264172;
然后您可以比较每个地区的CostPerLitre
if (candadianFuel.CostPerLitre > americanFuel.CostPerLitre)
{
cheapestFuel = americanFuel;
}
else
{
cheapestFuel = canadianFuel;
}
现在,当您打印到控制台时,您可以打印最便宜的燃料区域的名称:
Console.WriteLine("The cheaper gas is: {0}", cheapestFuel.Name);
你的逻辑没有处理的一件事是燃油价格相等。如果它们相等,那么你将始终打印加拿大燃料是最便宜的。