优秀的编程知识分享平台

网站首页 > 技术文章 正文

第二章:C# 基础语法_c#有什么语法格式

nanyue 2025-02-21 14:35:37 技术文章 2 ℃

2.1 变量与数据类型

在 C# 中,变量是用于存储数据的容器。每个变量都有一个特定的数据类型,决定了它可以存储的数据种类和大小。

常见的数据类型:

  • int:整数类型,例如 int age = 25;
  • double:双精度浮点数,例如 double price = 19.99;
  • string:字符串类型,例如 string name = "John";
  • bool:布尔类型,例如 bool isStudent = true;

示例代码:

csharp

复制

int age = 25;
double price = 19.99;
string name = "John";
bool isStudent = true;

Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
Console.WriteLine("Price: " + price);
Console.WriteLine("Is Student: " + isStudent);

2.2 运算符与表达式

C# 提供了多种运算符,用于执行各种操作,如算术运算、比较运算和逻辑运算。

常见的运算符:

  • 算术运算符:+, -, *, /, %
  • 比较运算符:==, !=, >, <, >=, <=
  • 逻辑运算符:&&, ||, !

示例代码:

csharp

复制

int a = 10;
int b = 20;

int sum = a + b;
int difference = a - b;
int product = a * b;
double quotient = (double)a / b;

bool isEqual = (a == b);
bool isGreater = (a > b);

Console.WriteLine("Sum: " + sum);
Console.WriteLine("Difference: " + difference);
Console.WriteLine("Product: " + product);
Console.WriteLine("Quotient: " + quotient);
Console.WriteLine("Is Equal: " + isEqual);
Console.WriteLine("Is Greater: " + isGreater);

2.3 控制流语句

控制流语句用于控制程序的执行流程。常见的控制流语句包括 if、switch、for、while 等。

if语句:

csharp

复制

int age = 18;

if (age >= 18)
{
    Console.WriteLine("You are an adult.");
}
else
{
    Console.WriteLine("You are a minor.");
}

for循环:

csharp

复制

for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Iteration: " + i);
}

while循环:

csharp

复制

int i = 0;
while (i < 5)
{
    Console.WriteLine("Iteration: " + i);
    i++;
}

2.4 数组与集合

数组是用于存储相同类型数据的集合。C# 中的数组是固定大小的,但可以通过集合类(如 List)来动态管理数据。

数组示例:

csharp

复制

int[] numbers = new int[5] { 1, 2, 3, 4, 5 };

for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine("Number: " + numbers[i]);
}

List示例:

csharp

复制

using System.Collections.Generic;

List names = new List();
names.Add("John");
names.Add("Jane");
names.Add("Doe");

foreach (string name in names)
{
    Console.WriteLine("Name: " + name);
}

课后练习题

  1. 简答题
  2. C# 中的常见数据类型有哪些?请举例说明。
  3. 什么是运算符?C# 中有哪些常见的运算符?
  4. if 语句和 switch 语句的区别是什么?
  5. 编程题
  6. 编写一个程序,要求用户输入一个数字,并判断它是奇数还是偶数。
  7. 编写一个程序,使用 for 循环输出 1 到 100 之间的所有偶数。
  8. 编写一个程序,使用 List 存储一组字符串,并输出其中的所有元素。
最近发表
标签列表