Computer Science Canada Figure out the numbers |
Author: | markEGz [ Sun Mar 26, 2006 4:07 pm ] |
Post subject: | Figure out the numbers |
Hi sorry for the noob question but i am stuck on this one problem.. "ask the user for an integer". Output the number of digits in the interger. Then output the sum of the digits. If i input 567 - i have 3 digits and also get their sum." I used the simple length command for the # of digits but how can i really figure their sum out? i tried working my way using char so it tracks down every number that is inputed in the get statement but couldnt figure it out Please help me with some ideas, thanks! |
Author: | Tony [ Sun Mar 26, 2006 4:18 pm ] |
Post subject: | |
math! basically each digit is located powers of 10. floor() rounds real values down. |
Author: | chrispminis [ Sun Mar 26, 2006 4:40 pm ] | ||
Post subject: | |||
Well, since you are using length, I'm assuming your reading the integer as a string so, you merely have to convert each digit to an integer with strint. Then add them together.
Hope that's what you were looking for ![]() |
Author: | cool dude [ Sun Mar 26, 2006 5:19 pm ] |
Post subject: | |
pretty nice chrispminis! i actually did this prog in 5 minutes approximately because i kinda did it the long way by just getting the remainders and seperating each digit i.e. first get the thousands digit by dividing by 1000 and so on... however mine was more code so i like your way better! ![]() |
Author: | chrispminis [ Sun Mar 26, 2006 6:42 pm ] |
Post subject: | |
Yeah, I know what you mean. I would've posted that, but Tony already did and since he mentioned length, I figured he was doing it with strings first. I did what you did a while ago when I was supposed to be learning the mod function. |
Author: | markEGz [ Sun Mar 26, 2006 8:28 pm ] |
Post subject: | rofl.. |
lmao, thanks alot i kind of went crazy and came up with this ^^^ var chars : array char of boolean var numInput : char var numCount : int var numLength : int := 0 var num : int := 0 var exitloop := false put "Please input your number * put a space after your last digit " loop Input.KeyDown (chars) get numInput if numInput >= '1' and numInput <= '9' then numLength := numLength + 1 num := num + ord (numInput)-48 end if if chars (KEY_ENTER) then exitloop := true end if exit when numInput = ' ' |
Author: | Delos [ Sun Mar 26, 2006 8:56 pm ] |
Post subject: | |
Please use [code] tags when you post. Also, it doesn't look like you've posted all of your code (the loop is incomplete). Why, may I ask, are you using both Input.KeyDown() and get? A bit of a waste. Choose one. (And yes, it is possible to detect 'Enter' with get...well, with getch()). |