Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Prompts and Math... 2 + 5 = 25?

I'm having some trouble in Sugarcube with a piece of code that lets the player decide a variable and then compares it to another to give them a sum. However, results are not very pleasing.

<<set $n1 to prompt("What number do you want this to be")>>

<<set $n2 to 5>>

$n1 and $n2 together make <<print $n1 + $n2>>

If I set $n1 to be 2, then that would make this a 2 + 5 equation, wouldn't it? But the answer turns out to be 25, and not 7. I'm not sure why this is happening, but I have a feeling it might be because it treats $n1 as a string and $n2 as an integer. Is there anyway I can get this to cooperate?

Any help is appreciated.

Comments

  • edited September 2015
    Yes, it's because you're adding a string to a number.

    If you want $n1 to always be a number, use Number() to parse it. For example:
    <<set $n1 to Number(prompt("What number do you want this to be"))>>
    <<if isNaN($n1) or not isFinite($n1)>>
    	Yell at the player and make them try again, because they entered something which
    	cannot be parsed into a number (well, a usable number, at any rate).
    <<else>>
    	The player entered a valid number.  Rejoice!
    <</if>>
    
    The reason for the check is because you can't control what the player may enter.
Sign In or Register to comment.