Hi all,
New to programming in general. I’m creating a program for school that calculates PI. I have the math working just fine but I want the user to enter a number, then grab this number and pass it to my procedure to perform my calculations. My code is below - I can’t get the input from the keyboard to work. About 2/3 of the way down the code you will see a comment saying *** THIS ISN’T WORKING YET **. Not sure what I’m doing wrong.
Any pointers to articles or videos (answer’s helpful too
) would be appreciated.
-- Assignment 7
-- Use this function to perform your initial setup
function setup()
end
function dothemath (a)
-- setup variables
-- first variable - fac - changes from +1 to -1 on each loop
-- this is so the formula will go number 1 - number 2 + number 3 ....
fac = 1
sum = 0
for i = 1, a do
term = fac / (2 * i - 1)
fac = fac * -1
sum = sum + term
end
pi = (4*sum)
end
-- when touched the keyboard will display
function touched(touch)
if touch.state==ENDED then
showKeyboard()
end
end
-- if the 'return' key is pressed on the keyboard,
-- hide the keyboard
function keyboard(key)
if key == "\
" then
hideKeyboard()
end
end
-- This function gets called once every frame
function draw()
-- This sets a dark background color
background(40, 40, 50)
-- This sets the line thickness
strokeWidth()
-- Do your drawing here
fill(122, 255, 0, 255)
fontSize(25)
font("Baskerville-bold")
-- writes the text for correct counter
text("How many iterations?",WIDTH*.5,HEIGHT*.8)
fontSize(20)
text("(Touch screen to enter number)",WIDTH*.5,HEIGHT*.75)
fontSize(25)
-- grab keyboard input, convert to number and pass to function
-- to do the math
-- ***** THIS ISN"T WORKING YET ***
a = keyboardBuffer()
if a ~= nil then
answer = tonumber("a")
-- this is what I want to do
-- pass in the keyboard answer, convert it to a number
-- and calculate the answer
-- dothemath(answer)
-- hard code an answer for now to ensure it works
-- which it does!
dothemath(4)
-- print answer to screen
text("PI is ", WIDTH*.5,HEIGHT*.40)
text(pi, WIDTH*.5,HEIGHT*.35)
end
end