求1-100之间的质数 分别用for while do-while三种语句,C#
时间: 2024-09-19 11:17:45 浏览: 57
在C#中,求1-100之间的质数可以使用For、While和Do-While循环分别编写如下:
**使用For循环:**
```csharp
using System;
public class PrimeNumbers
{
static void Main()
{
int limit = 100;
for (int i = 2; i <= limit; i++)
{
if (IsPrime(i))
{
Console.Write(i + " ");
}
}
}
static bool IsPrime(int number)
{
if (number < 2) return false;
for (int j = 2; j * j <= number; j++)
{
if (number % j == 0)
{
return false;
}
}
return true;
}
}
```
**使用While循环:**
```csharp
using System;
public class PrimeNumbers
{
static void Main()
{
int i = 2, limit = 100;
while (i <= limit)
{
if (IsPrime(i))
{
Console.Write(i + " ");
}
i++;
}
}
static bool IsPrime(int number)
{
if (number < 2) return false;
for (int j = 2; j * j <= number; j++)
{
if (number % j == 0)
{
return false;
}
}
return true;
}
}
```
**使用Do-While循环:**
```csharp
using System;
public class PrimeNumbers
{
static void Main()
{
int i = 2, limit = 100;
do
{
if (IsPrime(i))
{
Console.Write(i + " ");
}
i++;
} while (i <= limit);
}
static bool IsPrime(int number)
{
if (number < 2) return false;
for (int j = 2; j * j <= number; j++)
{
if (number % j == 0)
{
return false;
}
}
return true;
}
}
```
阅读全文