[英]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
I also need to use the function to test the parity of the number.我还需要使用 function 来测试数字的奇偶性。 When I enter a few numbers (1,2,3,4 and then 0) the program shows "9, 0 ".当我输入几个数字(1、2、3、4,然后是 0)时,程序会显示“9, 0”。 I'm not sure why我不知道为什么
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;
}
Two mistakes inside your loop:循环中的两个错误:
isEven(a);
if(true){
Even = Even + a
};
if(false){
Odd = Odd + a
};
The first one is that you're calling isEven
and not using the result.第一个是您正在调用isEven
而没有使用结果。 In the if
you're literally just using if(true)
and if(false)
, so you will always go in the first one and never in the second. if
您实际上只是使用if(true)
和if(false)
,那么您将始终在第一个中使用 go 而在第二个中永远不会。
The second mistake is that each time you're adding the entered number a
instead of 1, which is what you want if you need the amount of even/odd numbers.第二个错误是每次您添加输入的数字a
而不是 1,如果您需要偶数/奇数的数量,这就是您想要的。
So, keeping your (rather unusual) structure, you would have:因此,保持您的(相当不寻常的)结构,您将拥有:
var test = isEven(a);
if(test === true){
Even = Even + 1;
}
if(test === false){
Odd = Odd + 1;
}
In a more traditional way, I would suggest:以更传统的方式,我建议:
if(isEven(a)){
Even = Even + 1;
} else {
Odd = Odd + 1;
}
Try using this.尝试使用这个。
You had some problems: 1.Suppose you type 1 the prompt will close and while first iteration will continue.您遇到了一些问题: 1.假设您键入 1,提示将关闭,而第一次迭代将继续。 You open a new prompt so 1 will never be calculated.您打开一个新提示,因此永远不会计算 1。
let a = parseInt(prompt("Enter a number:"));
while (a != 0 ) {
a = parseInt(prompt("Enter a number:"));
l 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.