It looks like you're new here. If you want to get involved, click one of these buttons!
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.
-- 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 == "\n" 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
Comments
@oarnone
Is this what your looking for?
You can use this for the keyboard and then use the variable str the for calculations
@oarnone The code answer=tonumber("a") should be answer=tonumber(a) . When you call hideKeyboard(), that clears the keyboardBuffer, so you should move it to a variable before the call. Also, when you post code, put 3 ~'s on a line before and after the code so it formats correctly.
@oarnone Try making these changes
@oarnone I posted this somewhere on the forum awhile ago, but I couldn't find it, so here it is again. It calculates digits of Pi. Just change the value for digits in the code. I'm not sure what the limit is for digits. Just in case you're interested.
EDIT: I used this link to create the code below.
Thanks everyone. I will try this out today.
Got it working.. Thanks for the help.