javascript中用while和if语句实现1到100之间所有奇数之和、所有偶数之和,并计算出奇数和偶数的总个数。

2024-11-27 04:36:12
推荐回答(4个)
回答1:

var i=1;
var sum1=0;
var cont1=0;
var sum2=0;
var cont2=0;
while(i<100){
if(i%2==0){
sum1+=i
count1++;
}else{
sum2+=i
count2++;
}
i++;
}
alert("奇数之和"+sum1+"奇数总数"+count1);
alert("偶数之和"+sum2+"偶数总数"+count2);

回答2:

var
scount1=0;
var
scount2=0;
var
ssum1=0;
var
ssum2=0;
var
i
=1;
while
(i<=100){
if(i%2==0){
scount2
+=1;
ssum2
+=i;
}else{
scount1
+=1;
ssum1
+=
i;
}
i++;
}
document.write
("奇数的个数是:"+scount1+"
");
document.write("所有奇数之和为:"+ssum1+"
");
document.write
("偶数的个数是:"+scount2+"
");
document.write("所有偶数之和为:"+ssum2+"
");

回答3:

var
i=1;
var
sum1=0;
var
cont1=0;
var
sum2=0;
var
cont2=0;
while(i<100){
if(i%2==0){
sum1+=i
count1++;
}else{
sum2+=i
count2++;
}
i++;
}
alert("奇数之和"+sum1+"奇数总数"+count1);
alert("偶数之和"+sum2+"偶数总数"+count2);

回答4:

var scount1=0;
var scount2=0;
var ssum1=0;
var ssum2=0;
var i =1;
while (i<=100){
if(i%2==0){
scount2 +=1;
ssum2 +=i;
}else{
scount1 +=1;
ssum1 += i;
}
i++;
}

document.write ("奇数的个数是:"+scount1+"
");
document.write("所有奇数之和为:"+ssum1+"
");
document.write ("偶数的个数是:"+scount2+"
");
document.write("所有偶数之和为:"+ssum2+"
");