0

I am coding a calculator and I was trying to print the division equation's answer, but instead it converted fractions to decimals. I am running Lua 5.2.4

 print ("\n\tWhat math symbol will you use?") 
      ms = io.read()

-- Main function
 function TYPCALC() 

        --If user typed certain math symbols
  if (ms == "division") then

      print ("\n\tWhat number will be divided to?")
          local rn = io.read()

      print ("\n\tWhat will be dividing?")
          local ln = io.read()

          --convert users answers in to strings
          local cln = tonumber(ln)
          local crn = tonumber(rn)

          --do equasion
          io.write (ln / rn)
       end;         

  end ;

    TYPCALC()
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
robotbeta05
  • 41
  • 1
  • 4

2 Answers2

2

Lua does not have a fraction type. You'll have to calculate the numerator and denominator yourself. Then print it.

If you just print or write (number/number2) that expression will be evaluated first, resulting in a decimal number. The function will use a local copy of that number then.

local denominator = 12 -- or some calculated value in your case
local numerator = 1

print(numerator .. "/" .. denominator)

will print 1/12

Another remark:

--convert users answers in to strings
local cln = tonumber(ln)
local crn = tonumber(rn)

If you want to convert a number to a string, you have to use tostring(), not tonumber()

Piglet
  • 27,501
  • 3
  • 20
  • 43
  • I meant to use tonumber(), I just did a typo with the comment. Sorry about that. Also, I am not trying to print fractions, I am trying to print the answer to the division equasion. Sorry again if I didn't clarify well enough. – robotbeta05 Aug 18 '17 at 20:25
  • @robotbeta05 If you're not trying to print fractions, you should edit your question to make it clear what you're trying to do. – Tanner Swett Aug 21 '17 at 21:32
-2

I fixed my bug, it turns out that I had to switch the variables places to do the division. Normally you should not have to do this for equations in Lua, but I had to. I ran into this same problem with subtraction, and it fixed that too. Thanks for everyone's help. Here is my change:

io.write (ln / rn)

to

io.write (rn / ln)
robotbeta05
  • 41
  • 1
  • 4