Page 1 of 1

javascript problem...

PostPosted: Sun May 07, 2006 6:50 pm
by sunet
Can someone please help me with this?
I can't get the total... I want to add all the results from 'num', but currently all it does is put the results next to each other.


Code: Select all
var num, total, count=0;

for(count=1; count<4; count++)
{
    num=prompt("please enter a number");

    total=num+num+num;
}

    document.write(total);

PostPosted: Sun May 07, 2006 11:12 pm
by Warrior4Christ
Javascript is a bad language IMHO, because variable can take any type of data and even turn from one data type to another, as you have just demonstrated.

The prompt function returns a *string* entered by the user, which you have stored in num. So num stores the two digits, say '8' and '2' instead of 82. Then the "+" operator appends two (three!) strings together rather than performing addition. So you must convert num from string to a number. To do that, you use:

num = parseInt(prompt("Please enter a number:"));

But also, if you are intending to display the sum of three numbers entered by the user, it wouldn't work as expected. It would just display 3 times the last number entered. What you want to do is add num onto what is already stored in total. So:

total = total + num;

And unless the top initialisation list initialises all three variables to 0, total will need to be initialised there too.

Also, it's a bit amiguous to say "count < 4" for the loop condition when you want it to go up to 3. So I prefer to say "count <= 3" if I want to count up to 3.

PostPosted: Mon May 08, 2006 12:23 am
by Kaligraphic
also, for statements set the counter variable for themselves, so you don't really need to initialize count to 0 when it's just going to be set to 1 anyway.

PostPosted: Tue May 09, 2006 1:56 pm
by sunet
Thank you very much for the help!!!

PostPosted: Wed May 10, 2006 4:45 pm
by Mithrandir
Kaligraphic wrote:also, for statements set the counter variable for themselves, so you don't really need to initialize count to 0 when it's just going to be set to 1 anyway.

Pedantic note, but it's always good practice to predefine all your variables. I would comment them, personally, but that's just me. (Feel free to check out my javascript on the chat page, I guess).