【问题标题】:how to have the return answer as a whole number如何将返回答案作为一个整数
【发布时间】:2020-01-16 03:45:55
【问题描述】:

我是 javascript 的初学者,我只是将这个程序作为一个练习,基本上可以在 7 次或更少的时间内猜出你的数字,但问题是我一直将 (Answer Variable) 作为十进制数,我希望它只是一个整数。我该怎么做?

console.log('I will guess the number you\'re thinking of in 7 guesses maximum\n\t\tThink of a number between 1 and 100')
console.log('\n\n')

let low = 0;
let high = 100;
let answer = (high + low) / 2
let guess = Number(prompt("Pick a number"))


for(let a = 1; a < 7; a++){
 console.log(`Is your number ${answer} ?`) 
  let ud = Number(prompt(`Press :  1-Larger,  2-Smaller,   3-Current Number`))
    if(ud == 1){
      low=answer
      answer=(high + low) / 2
    } else if (ud == 2){
      high=answer
      answer=(high + low) / 2
    } else if (ud == "c"){
      break;
    }
}
console.log(`This is magic`); ````

【问题讨论】:

  • Math.round()你试过了吗!!

标签: javascript int


【解决方案1】:

那是因为如果你将奇数除以 2,它总是会得到一个十进制数。你可以使用Math.floor

console.log('I will guess the number you\'re thinking of in 7 guesses maximum\n\t\tThink of a number between 1 and 100')
console.log('\n\n')

let low = 0;
let high = 100;
let answer = (high + low) / 2
let guess = Number(prompt("Pick a number"))


for (let a = 1; a < 7; a++) {
  console.log(`Is your number ${answer} ?`)
  let ud = Number(prompt(`Press :  1-Larger,  2-Smaller,   3-Current Number`))
  if (ud == 1) {
    low = answer
    answer = Math.floor((high + low) / 2)
  } else if (ud == 2) {
    high = answer
    answer = Math.floor((high + low) / 2)
  } else if (ud == "c") {
    break;
  }
}
console.log(`This is magic`);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    相关资源
    最近更新 更多