C#中用while和do,,while循环语句计算1-100的奇数和偶数和的代码怎么写

2024-11-25 01:58:20
推荐回答(2个)
回答1:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("使用While结构计算");
int oddSum = 0,evenSum=0, i = 1;
while (i <= 99)
{
oddSum += i;//这里的i为奇数,从1开始,此表达式用于求奇数的和
i += 1;//i变为了偶数
evenSum += i;//用于求偶数和
i += 1;//i变为了下一个奇数
}
Console.WriteLine("从1到100的奇数和为{0},偶数和为{1}", oddSum, evenSum);
Console.WriteLine();
Console.WriteLine("使用do While结构计算");
oddSum = 0;
evenSum = 0;
i = 1;
do
{
oddSum += i;
i += 1;
evenSum += i;
i += 1;
} while (i <= 99);
Console.WriteLine("从1到100的奇数和为{0},偶数和为{1}", oddSum, evenSum);
Console.ReadKey();

}
}
}

回答2:

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
ConsoleApplication5
{
class
Program
{
static
void
Main(string[]
args)
{
Console.WriteLine("使用While结构计算");
int
oddSum
=
0,evenSum=0,
i
=
1;
while
(i
<=
99)
{
oddSum
+=
i;//这里的i为奇数,从1开始,此表达式用于求奇数的和
i
+=
1;//i变为了偶数
evenSum
+=
i;//用于求偶数和
i
+=
1;//i变为了下一个奇数
}
Console.WriteLine("从1到100的奇数和为{0},偶数和为{1}",
oddSum,
evenSum);
Console.WriteLine();
Console.WriteLine("使用do
While结构计算");
oddSum
=
0;
evenSum
=
0;
i
=
1;
do
{
oddSum
+=
i;
i
+=
1;
evenSum
+=
i;
i
+=
1;
}
while
(i
<=
99);
Console.WriteLine("从1到100的奇数和为{0},偶数和为{1}",
oddSum,
evenSum);
Console.ReadKey();
}
}
}