Home > OS >  Javascript showing the biggest number
Javascript showing the biggest number

Time:12-03

script which loads consecutive numeric values until 0 is encountered, then find the highest value among the given numbers my script below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
<!---Napisz skrypt który pozwoli na wczytanie kolejnych wartości liczbowych aż do napotkania 0 następnie
wsród podanych liczb znajdź wartość największą-->
<script>

let tab = [], i = 0, max, min;
//wczytywanie danych
do
{

tab[i] = parseInt(prompt("Podaj jakąś wartość. \n Zero kończy wprowadzanie danych:"));
i  ;
}
 while(tab[i-1]);
 max = tab[0]; min = tab[0];
 for(i=1; i < tab.length-1; i  )
{
    if(tab[i]>max) max = tab[i];

}
document.write()

</script>
</body>
</html>

How to fix it?

if,else it should show the biggest and the lowest typed number

CodePudding user response:

The code looks almost correct, but there is a small mistake in the for loop. Currently, the loop is iterating from the second to the second-to-last element of the tab array. To fix this, the loop should start from the first element and iterate until the last element. This can be achieved by changing the for loop to:

for(i = 0; i < tab.length; i  )
{
    if(tab[i] > max) max = tab[i];
}

Additionally, it would be better to replace the document.write() statement with console.log() to print the result in the JavaScript console rather than on the web page itself. This can be done by changing the last line of the script to:

console.log("The maximum value is: "   max);

After making those changes, the complete script should be:

<script>

let tab = [], i = 0, max, min;
//wczytywanie danych
do
{

tab[i] = parseInt(prompt("Podaj jakąś wartość. \n Zero kończy wprowadzanie danych:"));
i  ;
}
 while(tab[i-1]);
 max = tab[0]; min = tab[0];
 for(i = 0; i < tab.length; i  )
{
    if(tab[i] > max) max = tab[i];
}
console.log("The maximum value is: "   max);

</script>

CodePudding user response:

you can do something like this

const numbers = []
while(true) {
 const num = parseInt(prompt('Insert a number. zero to exit'))
 if(num === 0){
  break;
 }
 numbers.push(num)
 
 console.log(`the max number entered is ${Math.max(...numbers)}`)
 console.log(`the min number entered is ${Math.min(...numbers)}`)

}

CodePudding user response:

Window.prompt() is easy to write in your code, but the experience it creates for the user can be quite disruptive. From the linked MDN documentation:

Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window).

In the case of your question, making use of a number input provides multiple advantages (non-blocking, built-in validation, etc.)

Here's an example of using a number input element and keeping track of the user's input history, which allows for an always updated value for min and max as the user commits new values:

If you want to prevent input of duplicate values, you could use a Set instead of an array.

const numbersElm = document.getElementById('numbers');
const minElm = document.getElementById('min');
const maxElm = document.getElementById('max');
const input = document.querySelector('input');
const button = document.querySelector('button');

const state = {
  numbers: [],
  min: NaN,
  max: NaN,
};

// Allow the user to commit values using the keyboard's Enter key:
input.addEventListener('keyup', (ev) => {
  if (ev.key === 'Enter') handleCommit();
});

// Or by clicking the button:
button.addEventListener('click', handleCommit);

function updateOutput () {
  numbersElm.textContent = state.numbers.join(', ');
  if (Number.isFinite(state.min)) minElm.textContent = state.min;
  if (Number.isFinite(state.max)) maxElm.textContent = state.max;
}

function parseInput () {
  const trimmed = input.value.trim();

  // Avoid invalid (or a lack of) input:
  if (!trimmed) return NaN;
  const number = Number(trimmed);
  if (Number.isNaN(number)) return NaN;

  // You can return the valid number now:
  // return number;

  // Or convert it to an integer first:
  return parseInt(number, 10);
}

function handleCommit () {
  const number = parseInput();

  // Cancel if the input is not valid:
  if (Number.isNaN(number)) {
    // Select the value in the input
    // so that the user can overwrite it easily (or modify it):
    input.select();
    return;
  }

  state.numbers.push(number);
  state.min = Math.min(...state.numbers);
  state.max = Math.max(...state.numbers);
  updateOutput();

  // Clear the input so that the user doesn't have to:
  input.value = '';
  input.focus();
}
* { box-sizing: border-box; } body, button { font-family: sans-serif; font-size: 1rem; } input[type="number"], #numbers { font-family: monospace; } button, input { font-size: 1rem; padding: 0.5rem; } #output { margin-bottom: 1rem; display: flex; flex-direction: column; gap: 1rem; }
<div id="output">
  <div id="numbers">Commit a number to get started</div>
  <div>Min: <span id="min"></span></div>
  <div>Min: <span id="max"></span></div>
</div>
<input type="number" />
<button>Commit number</button>

  • Related