Click here to Skip to main content
15,891,708 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
HTML
I am getting a false output...

The code is given below...

<html>
<head>
	<title> My test calculated cookie </title>
	
	<script type="text/javascript">
	function myFunction()
	{
				var num1=371;
				var num2;
				num2=num1;
				var rem=0;
				var cube=0;
				var sum=0;
				
				while(num1!=0)
				{
				    rem=num1%10;
				    cube=rem*rem*rem;
				    sum=sum+cube;
				    num1=num1/10;
				}	
				
				if(num2==sum)
				{
				    alert("The number is armstrong");
				}
				else
				{
				    alert("The number is not armstrong");
				}

            
	}
				
	</script>
		
	
	
</head>

<body onload="myFunction()">
<h1>hi</h1>
</body>
</html>



What i am getting ...
"The number is not armstrong"
whereas it is an armstrong number...

Anyone can help me please where I am doing the mistake....
Posted

I have got the solution...

JavaScript
function myFunction(myname,passkey)
	{
	            var num1 = passkey;
	            var username = myname;
				var num2;
				num2=num1;
				var rem=0;
				var cube=0;
				var sum=0;
				
				while(num1 != 0)
				{
				    rem = parseInt(num1 % 10);
				    cube = rem * rem * rem;
				    sum = sum + cube;
				    num1 = parseInt(num1 / 10);
				}	
				
				if(num2==sum)
				{
				    alert("The number is armstrong");
				}
				else
				{
				    alert("The number is not armstrong");
				}

            
	}


You were right Graham, its generating decimal number which creating further iterations to the loop..
 
Share this answer
 
I hadn't heard of an Armstrong number before, so I had to Google it.

Your problem is that num1 = num1 / 10 will give you 37.1 and not 37. The Math.floor() function should help you out there.
 
Share this answer
 
Comments
enhzflep 11-Oct-12 8:35am    
Bingo! Not sure which is the faster, though you can also use:

rem=(num1>>0)%10;

(num1>>0) converts a floating point number to an int. It truncates, as floor does.
Graham Breach 11-Oct-12 9:08am    
Good point - I tend to use "~~variable" for truncating in Javascript and another method I've seen is "variable|0".
enhzflep 11-Oct-12 9:16am    
Hmmm. Thank-you. 2 more tricks to add to the toolbox. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900