C# 查找成本,计算项目成本并包含 10% GST
Posted
技术标签:
【中文标题】C# 查找成本,计算项目成本并包含 10% GST【英文标题】:C# find cost, calculate the cost of item and include 10% GST 【发布时间】:2016-10-14 07:11:35 【问题描述】:我正在学习 C#,并被要求创建一个杂货程序。我被卡住了,似乎无法在网上找到任何可以帮助我的东西。我创建了一个杂货项目类,其属性包含名称和价格。我还创建了一个数量为整数的购买项目的子类。我现在需要创建一个方法来查找价格、计算价格并添加 10% 的 GST。关于如何做到这一点的任何想法。 这是我到目前为止所拥有的 - 任何帮助将不胜感激:
namespace Groceries1
class Program
static void Main(string[] args)
groceryItem mygroceryItem = new groceryItem();
mygroceryItem.play();
purchasedItem mypurchasedItem = new purchasedItem();
class groceryItem
private string myName = 0;
private int myPrice = 0;
public string Name
get
return myName;
set
myName = value;
public int Price
get
return myPrice;
set
myPrice = value;
class purchasedItem
private int myquantity = 0;
public int quantity
get
return myquantity;
set
myquantity = Price*quantity*1.1;
【问题讨论】:
【参考方案1】:你可以试试这个,
using System;
using System.Collections.Generic;
namespace Groceries
public class Program
public static void Main(string[] args)
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = "Fresh grocery";
freshGrocery.Price = 30;
freshGrocery.Weight = 0.5;
Grocery grocery = new Grocery();
grocery.Name = "Grocery";
grocery.Price = 50;
grocery.Quantity = 2;
ShoppingCart cart = new ShoppingCart();
cart.Orders = new List<GroceryItem>();
cart.Orders.Add(freshGrocery);
cart.Orders.Add(grocery);
double price = cart.Calculate();
Console.WriteLine("Price: 0", price);
abstract class GroceryItem
private string name;
private double price = 0;
public string Name
get
return name;
set
name = value;
public double Price
get
return price;
set
price = value;
public abstract double Calculate();
class FreshGrocery: GroceryItem
private double weight = 0;
public double Weight
get
return weight;
set
weight = value;
public override double Calculate()
return this.Price * this.Weight;
class Grocery: GroceryItem
private int quantity = 0;
private double gst = 10; // In Percentage
public int Quantity
get
return quantity;
set
quantity = value;
public override double Calculate()
double calculatedPrice = this.Price * this.Quantity;
// VAT
if(calculatedPrice > 0)
calculatedPrice += calculatedPrice * (gst/100);
return calculatedPrice;
class ShoppingCart
private List<GroceryItem> orders;
public List<GroceryItem> Orders
get
return orders;
set
orders = value;
public double Calculate()
double price = 0;
if(this.Orders != null)
foreach(GroceryItem order in this.Orders)
price += order.Calculate();
return price;
【讨论】:
您好 Aruna,感谢您提供建议的代码。我试过了,我收到代码错误 你能告诉我是什么错误,我可以解决它。我只是在这里直接编码,没有执行。 1.不能将类型“double”隐式转换为“int”。存在显式转换(您是否缺少演员表?)。 2. 无法将类型“int”隐式转换为“string”。 3.“Program.ShoppingCart.Calculate()”:并非所有代码路径都返回值 4.“List以上是关于C# 查找成本,计算项目成本并包含 10% GST的主要内容,如果未能解决你的问题,请参考以下文章