开发需求:从100倒数至指定正整数N并分离奇偶数字
Hey there! Let's fix up that code to meet your requirement of counting down from 100 to a user-input positive integer N, splitting even and odd numbers into separate lines. Here's a practical implementation that addresses your needs clearly:
<div id="results"></div> <script> function countDownAndSeparate() { // Get user input first let userInput = prompt("Please enter a positive integer N (≤ 100):", ""); if (!userInput) return; // Exit if user cancels the prompt // Convert input to integer and validate it const N = parseInt(userInput); if (isNaN(N) || N <= 0 || N > 100) { alert("Whoops! Please enter a valid positive integer that's no greater than 100."); return; } // Initialize arrays to hold our even and odd numbers const evenNumbers = []; const oddNumbers = []; // Loop from 100 all the way down to N (inclusive) for (let i = 100; i >= N; i--) { if (i % 2 === 0) { evenNumbers.push(i); // Add to evens if divisible by 2 } else { oddNumbers.push(i); // Add to odds otherwise } } // Turn our arrays into space-separated strings for display const evenString = evenNumbers.join(" "); const oddString = oddNumbers.join(" "); // Populate the results in the DOM const resultsContainer = document.getElementById("results"); resultsContainer.innerHTML = ` <p><strong>Even numbers:</strong> ${evenString}</p> <p><strong>Odd numbers:</strong> ${oddString}</p> `; } // Run the function when the page loads (you could also attach this to a button click!) countDownAndSeparate(); </script>
- Input Validation: Makes sure the user enters a valid number (no empty values, non-numeric text, or numbers outside the 1-100 range) to avoid errors.
- Categorization: Loops from 100 down to your input N, sorting each number into even or odd groups using a simple modulo check.
- Clean Output: Displays the results in a readable format with clear labels so you can easily tell which line is evens vs odds.
I noticed your provided test cases seem to have a small discrepancy (e.g., inputting 10 shows results stopping at 92/91 instead of 10). Assuming that was a typo, here's what you'd get with correct inputs matching the test case patterns:
- If you input 90, you'll get evens:
100 98 96 94 92 90and odds:99 97 95 93 91 - If you input 96, you'll get evens:
100 98 96and odds:99 97
If you actually wanted to count a fixed number of steps instead of stopping at N, we could adjust the loop to run (100 - N) times instead of going down to N—but based on your initial description, stopping at N is the right approach.
内容的提问来源于stack exchange,提问作者David Smith

