![](/img/trans.png)
[英]user enters amount on numbers then output the highest number javascript
[英]JavaScript:User enters numbers until he enters 0.Each numbers parity is determined and at the end,the total number of even and odd numbers is printed
我還需要使用 function 來測試數字的奇偶性。 當我輸入幾個數字(1、2、3、4,然后是 0)時,程序會顯示“9, 0”。 我不知道為什么
let Even = 0;
let Odd = 0;
let a = parseInt(prompt("Enter a number:"));
while (a != 0 ) {
a = parseInt(prompt("Enter a number:"));
isEven(a);
if(true){
Even = Even + a};
if(false){
Odd = Odd + a};
};
console.log(Even,Odd);
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}
循環中的兩個錯誤:
isEven(a);
if(true){
Even = Even + a
};
if(false){
Odd = Odd + a
};
第一個是您正在調用isEven
而沒有使用結果。 if
您實際上只是使用if(true)
和if(false)
,那么您將始終在第一個中使用 go 而在第二個中永遠不會。
第二個錯誤是每次您添加輸入的數字a
而不是 1,如果您需要偶數/奇數的數量,這就是您想要的。
因此,保持您的(相當不尋常的)結構,您將擁有:
var test = isEven(a);
if(test === true){
Even = Even + 1;
}
if(test === false){
Odd = Odd + 1;
}
以更傳統的方式,我建議:
if(isEven(a)){
Even = Even + 1;
} else {
Odd = Odd + 1;
}
嘗試使用這個。
您遇到了一些問題: 1.假設您鍵入 1,提示將關閉,而第一次迭代將繼續。 您打開一個新提示,因此永遠不會計算 1。
let a = parseInt(prompt("Enter a number:"));
while (a != 0 ) {
a = parseInt(prompt("Enter a number:"));
l
et Even = 0;
let Odd = 0;
let a = parseInt(prompt("Enter a number:"));
while (a != 0 ) {
var isEvenResult = isEven(a)
if(isEvenResult){
Even += parseInt(a);
}
else{
Odd += parseInt(a);
}
a = parseInt(prompt("Enter a number:"));
}`enter code here`
console.log(Even +','+ Odd);
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.