简体   繁体   English

修改 JavaScript/HTML 代码的问题

[英]Problem with modifying JavaScript/HTML code

so i've got a problem with modifying my code.所以我在修改我的代码时遇到了问题。 I need to edit my code so it will not only do it's purpose(the thing that it does now) but it will count from 1 to given number.我需要编辑我的代码,这样它不仅会达到目的(它现在所做的事情),而且会从 1 计数到给定的数字。 I wouldn't make this question but i need to complite that exercise ASAP and i'm struggling with it for like 5 lessons now.我不会提出这个问题,但我需要尽快完成该练习,我现在正在努力学习 5 节课。 The code is in Polish and it's simple.代码是波兰语的,很简单。 It's purpose for now is to calculate factorial of given number.现在的目的是计算给定数字的阶乘。 Here's the code:这是代码:

 function obliczSilnie(liczba) { var wynik = silnia(liczba); if (wynik > 0) { document.getElementById("result").innerHTML = "<h3 style'color:blue;'>Silnia liczby " + liczba + "wynosi: " + wynik + "</h3>"; } } function silnia(liczba) { if (liczba == 0 || liczba == 1) { return 1; } else if (liczba < 0) { error(); return -1; } var wynik = liczba * silnia(liczba - 1); return wynik; } function error() { document.getElementById("result").innerHTML = "<h3 style='color:red;'>Błąd: Nie można obliczyć silni dla liczby ujemnej; </h3>"; }
 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>Obliczanie silni</h1> <form name="myForm"> <p> <b>Podaj liczbę:</b> <input type="number" name="myNumber" value="0" size=2> </p> <input type="reset" value="Wyczyść"> <input type="button" value="Obilcz" onclick="obliczSilnie(document.myForm.myNumber.value)"> </form> <p id="result"></p> </body> </html>

I hope I understood your question correctly.我希望我能正确理解你的问题。 That's my solution:那是我的解决方案:

 function computeFactors(number) { //Here we use recursion with a for loop for(var i = 1;i < number;i++){ var result = factorial(i); if (result > 0) { document.getElementById("result").innerHTML += "<h3 style='color:blue;'> Factorial of " + i + " is: " + result + "</h3>"; } } } function factorial(number) { if (number == 0 || number == 1) { return 1; } else if (number < 0) { error(); return -1; } var result = number * factorial(number - 1); return result; } function error() { document.getElementById("result").innerHTML = "<h3 style='color:red;'>Error: Could not factorize a negative number; </h3>"; }
 <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>Factory calculation</h1> <form name="myForm"> <p> <b>Enter a number:</b> <input type="number" name="myNumber" value="0" size=2> </p> <input type="reset" value="Clear"> <input type="button" value="Calculate" onclick="computeFactors(document.myForm.myNumber.value)"> </form> <p id="result"></p> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM