Price fraction: Difference between revisions
Content added Content deleted
(Add Quackery) |
(Updated to work with Nim 1.4. Done heavy restructuring and simplification, but kept the algorithm.) |
||
Line 2,769: | Line 2,769: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
<lang nim>import |
<lang nim>import random, strformat |
||
# Representation of a standard value as an int (actual value * 100). |
|||
const |
|||
type StandardValue = distinct int |
|||
⚫ | |||
proc `<`(a, b: StandardValue): bool {.borrow.} |
|||
# outputs an int (=>float*100) |
|||
proc floatToPrice100(f: float): int = |
|||
⚫ | |||
⚫ | |||
if valu == 0: |
|||
result = 10 |
|||
⚫ | |||
dec(valu) |
|||
⚫ | |||
var indx: int = 2*int(valu/10)+int((valu%%10)/5) |
|||
result = pricemap[indx] |
|||
⚫ | |||
# str representation of an int (that is a representation of a float price) |
|||
proc price100ToStr(p: int): string = |
|||
⚫ | |||
result = "0.0" & $p |
|||
if p < 100: |
|||
result = "0." & $p |
|||
else: |
|||
result = "1.00" |
|||
⚫ | |||
var i: int = 0 |
|||
proc toStandardValue(f: float): StandardValue = |
|||
for x in 0 .. 10: |
|||
## Convert a float to a standard value (decimal value multiplied by 100). |
|||
i = random(101) |
|||
⚫ | |||
echo("Price for ", i.price100ToStr(), ", is: ", float(i/100).floatToPrice100().price100ToStr())</lang> |
|||
⚫ | |||
if value == 0: return StandardValue(10) |
|||
dec value |
|||
⚫ | |||
let index = 2 * (value div 10) + (value mod 10) div 5 |
|||
result = StandardValue(Pricemap[index]) |
|||
proc `$`(price: StandardValue): string = |
|||
## Return the string representation of a standard value. |
|||
if price < StandardValue(10): "0.0" & $int(price) |
|||
elif price < StandardValue(100): "0." & $int(price) |
|||
⚫ | |||
when isMainModule: |
|||
⚫ | |||
⚫ | |||
let price = rand(1.01) |
|||
echo &"Price for {price:.2f} is {price.toStandardValue()}"</lang> |
|||
{{out}} |
{{out}} |
||
A random output something like: |
A random output looking something like this: |
||
<pre>Price for 0. |
<pre>Price for 0.88 is 0.94 |
||
Price for 0. |
Price for 0.58 is 0.70 |
||
Price for 0. |
Price for 0.67 is 0.78 |
||
Price for 0. |
Price for 0.53 is 0.66 |
||
Price for 0. |
Price for 0.56 is 0.66 |
||
Price for 0. |
Price for 0.02 is 0.10 |
||
Price for 0. |
Price for 0.61 is 0.70 |
||
Price for 0. |
Price for 0.41 is 0.58 |
||
Price for 0. |
Price for 0.22 is 0.38 |
||
Price for 0. |
Price for 0.91 is 0.98 |
||
Price for 0. |
Price for 0.42 is 0.58</pre> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |