我在教学/帮助学生编程.
我记得当我开始时,以下过程总能帮助我; 它看起来非常直观,我想知道其他人是否有类似的方法.
随着时间和实践,我似乎忘记了从问题描述转到编码解决方案有多难,但是,通过应用这种方法,我设法学习如何编程.
所以对于项目描述如下:
系统必须根据以下规则计算物品的价格(规则的描述......客户,折扣,可用性等等.等等.)
我的第一步是了解问题所在.
然后识别项目,规则变量等.
伪代码类似于:
function getPrice( itemPrice, quantity , clientAge, hourOfDay ) : int
if( hourOfDay > 18 ) then
discount = 5%
if( quantity > 10 ) then
discount = 5%
if( clientAge > 60 or < 18 ) then
discount = 5%
return item_price - discounts...
end
Run Code Online (Sandbox Code Playgroud)
然后将其传递给编程语言..
public class Problem1{
public int getPrice( int itemPrice, int quantity,hourOdDay ) {
int discount = 0;
if( hourOfDay > 10 ) {
// uh uh.. U don't know how to calculate percentage...
// create a function and move on.
discount += percentOf( 5, itemPriece );
.
.
.
you get the idea..
}
}
public int percentOf( int percent, int i ) {
// ....
}
}
Run Code Online (Sandbox Code Playgroud)
你有没有采用类似的方法?有人教你一个类似的方法,或者你发现了自己(就像我做的那样:()
jop*_*jop 11
我通过测试驱动的方法.
- simple calculations (no discounts and concessions) with:
- single item
- two items
- maximum number of items that doesn't have a discount
- calculate for discounts based on number of items
- buying 10 items gives you a 5% discount
- buying 15 items gives you a 7% discount
- etc.
- calculate based on hourly rates
- calculate morning rates
- calculate afternoon rates
- calculate evening rates
- calculate midnight rates
- calculate based on buyer's age
- children
- adults
- seniors
- calculate based on combinations
- buying 10 items in the afternoon
Run Code Online (Sandbox Code Playgroud)
使用Nunit和C#的示例.
[Test] public void SingleItems()
{
Assert.AreEqual(5, GetPrice(5, 1));
}
Run Code Online (Sandbox Code Playgroud)
实现使用:
public decimal GetPrice(decimal amount, int quantity)
{
return amount * quantity; // easy!
}
Run Code Online (Sandbox Code Playgroud)
然后转到这两个项目.
[Test]
public void TwoItemsItems()
{
Assert.AreEqual(10, GetPrice(5, 2));
}
Run Code Online (Sandbox Code Playgroud)
实现仍然通过测试,所以继续进行下一个测试.
这并不能保证您将创建最有效的算法,但只要您知道要测试的内容并且一切都通过,它将保证您获得正确的答案.
老派的OO方式:
[这种方法先于CRC卡,但它已经很久了(超过20年),我不记得我在哪里学到了它]
| 归档时间: |
|
| 查看次数: |
1689 次 |
| 最近记录: |