用JavaScript实现100以内自然数求和
2015-03-2419:51:46
//第一种方法: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>实现100以内自然数求和</title> </head> <script language='javascript'> //实现100以内自然数求和,网页预览效果如图 var i=1,sum=0; //声明变量i和sum; while(i<=100){ sum+=i;i++ } document.write('1+2+3+...+100='+sum);//向页面中输入结果 </script> <body> </body> </html> //第二种方法: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>100以内自然数求和</title> </head> <script> var sum=0; for(var i=1;i<=100;i++){ sum+=i; } document.write('1+2+3+...+100='+sum); </script> <body> </body> </html> //第三种方法: <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>100以内自然数求和</title> <script> var i=1,sum=0; do{ sum+=i; i++ } while(i<=100){ document.write('1+2+3+...+100='+sum); } </script> </head> <body> </body> </html>
个人喜好比较喜欢用for循环,感觉for的逻辑比较符合思维方式