[英]Change calculator using C#
我正在嘗試編寫一個程序來獲取支付的價格和金額並輸出零錢面額。 我遇到以下問題。
這是代碼
using System;
namespace ChangeCalulator
{
class Program
{
static void Main(string[] args)
{
Console.Write("Item Price: ");
int price = Convert.ToInt32(Console.ReadLine());
Console.Write("Amount Paid: ");
int paid = Convert.ToInt32(Console.ReadLine());
while (paid < pice)
{
Console.WriteLine("You have paid less than the price");
Console.Write("Paid: ");
paid = Convert.ToInt32(Console.ReadLine());
}
decimal changeamount = paid - price;
Change change = new Change(changeamount);
//This displays the change based on each denominantion
Console.WriteLine($"Hundred SEK Bills: {change.HundredBills}");
Console.WriteLine($"Fifty SEK Bills: {change.FiveBills}");
Console.WriteLine($"Twenty SEK Bills: {change.TwentyBills}");
Console.WriteLine($"Ten SEK Bills: {change.TenBills}");
Console.WriteLine($"Five SEK Bills: {change.FiveBills}");
Console.WriteLine($"One SEK: {change.Bills}");
Console.ReadKey();
}
}
//The Change class will create a public integer variable for each denomination and store the values.
public class Change
{
private int changeamount;
public int HundredBills { get; }
public int FiftyBills { get; }
public int TwentyBills { get; }
public int TenBills { get; }
public int FiveBills { get; }
public int Bills { get; }
//This calculates the number of each denomination the amount equals
public Change(decimal price)
{
HundredBills = (int)(changeamount / 100);
price %= 100;
FiftyBills = (int)(changeamount / 50);
price %= 50;
TwentyBills = (int)(changeamount / 20);
price %= 20;
TenBills = (int)(changeamount / 10);
price %= 10;
FiveBills = (int)(changeamount / 5);
price %= 5;
Bills = (int)(changeamount / 1);
price %= 1;
}
}
}
非常感謝您對此的任何幫助。
在構造函數public Change(decimal price)
中,您需要使用price
:
public Change(decimal price)
{
HundredBills = (int)(price / 100);
price %= 100;
FiftyBills = (int)(price / 50);
price %= 50;
TwentyBills = (int)(price / 20);
price %= 20;
TenBills = (int)(price / 10);
price %= 10;
FiveBills = (int)(price / 5);
price %= 5;
Bills = (int)(price / 1);
price %= 1;
}
然后,您可以刪除不需要的changeamount
字段。
工作演示: https://dotnetfiddle.net/NbyZPc
至於不打印 0 金額,一個簡單的if (theValue > 0)
檢查每個 WriteLine 應該可以完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.