溫馨提示×

C#中怎么使用條件語句和循環(huán)語句

c#
小億
93
2024-03-06 15:21:07
欄目: 編程語言

在C#中,條件語句一般使用if語句來實現(xiàn),循環(huán)語句一般使用for循環(huán)、while循環(huán)、do-while循環(huán)等來實現(xiàn)。以下是一些示例:

  1. 使用if語句實現(xiàn)條件語句:
int num = 10;

if (num > 0)
{
    Console.WriteLine("num is positive");
}
else if (num < 0)
{
    Console.WriteLine("num is negative");
}
else
{
    Console.WriteLine("num is zero");
}
  1. 使用for循環(huán)實現(xiàn)循環(huán)語句:
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
  1. 使用while循環(huán)實現(xiàn)循環(huán)語句:
int i = 0;
while (i < 5)
{
    Console.WriteLine(i);
    i++;
}
  1. 使用do-while循環(huán)實現(xiàn)循環(huán)語句:
int i = 0;
do
{
    Console.WriteLine(i);
    i++;
} while (i < 5);

以上是C#中使用條件語句和循環(huán)語句的一些基本示例。根據(jù)具體需求,可以根據(jù)實際情況選擇合適的語句來實現(xiàn)邏輯控制。

0