用JAVA程序 分别求出1--100间的奇数,偶数之和.

(奇数之和用while语句,偶数之和用do--while语句)
2024-11-24 10:04:31
推荐回答(5个)
回答1:

public class ComputeOddEven
{
public static void main(String[] args)
{
int sumOdd=0;//求奇数和的变量
int sumEven=0;//求偶数之和的变量
for(int i=1;i<=100;i++)
{
while(i%2!=0)
{
sumOdd+=i;
break;
}
do
{
if(i%2==0)
{
sumEven+=i;
}
break;
}while(i>100);
}
System.out.println("奇数之和为"+sumOdd);
System.out.println("偶数之和为"+sumEven);
}
}

回答2:

//////////////////////////////////////////////////
// requestOddNumber o=2n-1
// requestEvenNumber e=2n
// o,e∈N, o,e∈(1,100)
// ∑o=3+5+...+99
// ∑e=2+4+...+98
//////////////////////////////////////////////////
package math;
public class oen {
public static int sumOn(int m,int n){
if(m>n){m^=n;n^=m;m^=n;}
m+=1+(m&1);int sum=0;
while(m return sum;
}
public static int sumEn(int m,int n){
if(m>n){m^=n;n^=m;m^=n;}
m+=1+((m+1)&1);int sum=0;
while(m return sum;
}
public static void main(String[] args){
int m=1;int n=100;
System.out.println(m+"到"+n+"间奇数的和为:"+sumOn(m,n));
System.out.println(m+"到"+n+"间偶数的和为:"+sumEn(m,n));
}
}

回答3:

int i = 1;
int count = 0;
while (i < 101)
{
if (i % 2 != 0)
{
count += i;
}
i++;
}
System.out.println("奇数之和为:" + count);
i = 1;
count = 0;
do
{
if (i % 2 == 0)
count += i;
i++;
} while (i < 101);
System.out.println("偶数之各为:" + count);

回答4:

public class test{
static void jiShu(){
int i=0;
int result = 0;
while(i <= 100){
if((i&1) == 0)
result += i;
i++;
}
System.out.println("奇数和为: " + result);
}
static void ouShu(){
int i=0;
int result = 0;
do{
if((i&1) != 0)
result += i;
i++;
}while(i <= 100);
System.out.println("偶数和为: " + result);
}
public static void main(String[] args){
jiShu();
ouShu();
}
}

回答5:

public
class
ComputeOddEven
{
public
static
void
main(String[]
args)
{
int
sumOdd=0;//求奇数和的变量
int
sumEven=0;//求偶数之和的变量
for(int
i=1;i<=100;i++)
{
while(i%2!=0)
{
sumOdd+=i;
break;
}
do
{
if(i%2==0)
{
sumEven+=i;
}
break;
}while(i>100);
}
System.out.println("奇数之和为"+sumOdd);
System.out.println("偶数之和为"+sumEven);
}
}