【发布时间】:2020-06-30 20:31:18
【问题描述】:
这是一个作业,请看问题和我在下面写的代码。
问题: 在美国硬币系统中,一便士是基本硬币,它等于美分,一个镍相当于5美分,一角硬币相当于10美分,四分之一相当于25美分,半美元相当于到 50 美分。设计并实现一个程序,该程序将利用以下所示的功能。每个函数都有一个 int 形式参数 Amount。 a) HalfDollars ():计算可用于找零的最大半美元数量。 b) Quarters():计算可用于更改 Amount 的最大季度数 c) Dimes ():计算可用于更改 Amount 的最大硬币数量 d) Nickels () : 计算可用于更改 Amount 的最大镍数
我写的代码:
//Question 1
//please note, i dont have comments everywhere
{
public class MoneyCalc
{
public int Amount;
//a)
public void Half_Dollar()
{
int hd = 2;
int hdOutput = Amount * hd;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + hdOutput);
}
//b)
public void Quater()
{
int q = 4;
int qOutput = Amount * q;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + qOutput);
}
//c)
public void Dimes()
{
int d = 10;
int dOutput = Amount * d;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + dOutput);
}
//d)
public void Nickles()
{
int n = 20;
int nOutput = Amount * n;
Console.WriteLine("The maximum number of half dollars for " + Amount + " is: " + nOutput);
}
}
class Program
{
static void Main(string[] args)
{
//the main program.
//everything is initialised here.
//gets the amount the ser wants to calculate through user input in a string and converts to to an integer.
Console.WriteLine("Please enter an amount to calculate:");
string userAmount = Console.ReadLine();
int amount = Int32.Parse(userAmount);
//users have to make a selection from this list.
Console.WriteLine("");
Console.WriteLine("Please choose what you want to calculate you amount to (Select the number):");
Console.WriteLine("1. Half Dollar");
Console.WriteLine("2. Quater");
Console.WriteLine("3. Dime");
Console.WriteLine("4. Nickel");
//gets the users input(their choice) in a string and coverts it to an integer
string userChoice = Console.ReadLine();
int choice = Int32.Parse(userAmount);
if (choice == 1)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Half_Dollar();
}
else if (choice == 2)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Quater();
}
else if (choice == 3)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Dimes();
}
else if (choice == 4)
{
MoneyCalc moneycalc = new MoneyCalc();
moneycalc.Amount = amount;
moneycalc.Nickles();
}
else
{
Console.WriteLine("Invalid Option");
}
}
}
}
【问题讨论】:
-
你给了它什么输入?它给出了什么输出?你期待什么?
-
请阅读How to Ask。您不仅需要学习编程,还需要学习调试。首先写下一些输入和您期望的输出。然后运行您的程序,当实际输出与您的预期不符时,设置断点并单步执行您的代码以检查您的变量。如果您需要帮助,您需要向我们解释您期望的行为和观察到的内容,以及您尝试修复代码的内容。编辑:简而言之,或者@Sweeper 所说的内容。
-
@PaulF 那部分看起来不错 - 有两个半美元 金额是 1 美元,十角钱等。
-
赋值指定你需要为你的函数使用一个参数。还要查看返回值而不是从中打印
-
抱歉含糊不清。因此,当我在控制台中运行代码时,它会要求我输入要计算的值,然后选择选项(如我所料)。一旦我选择了该选项,控制台窗口就会关闭。我会尝试查看返回值。
标签: c# function class methods return