C#语法快速热身
一、C#中的條件語句:
1.if(條件){
//代碼
}else{
//代碼
}
2.多重if:
if(條件){
//代碼
}else if(條件){
//代碼
}else{
//代碼
}
3.嵌套if
if(條件){
if(條件){
//代碼
}else{
//代碼
}
}else {
//代碼
}
4.switch結構:
switch(整型、字符串){
case 1:
//代碼
break;
case 2:
//代碼
break;
default:
//代碼
break;
}
二、C#中的數(shù)組:
1.定義數(shù)組:
(1)數(shù)據(jù)類型 [] 數(shù)組名 = new 數(shù)據(jù)類型 [5];
(2)數(shù)據(jù)類型 [] 數(shù)組名 = new 數(shù)據(jù)類型 [5]{1,2,3,4,5}
(3)數(shù)據(jù)類型 [] 數(shù)組名 = {1,2,4}
(4)數(shù)據(jù)類型 [] 數(shù)組名 = new 數(shù)據(jù)類型 []{1,2,3,4,5};
2.給數(shù)組中賦值:
數(shù)組名[下標] = 值
3.獲取數(shù)組的長度:
數(shù)組名.Length
三、C#中的循環(huán):
while(循環(huán)條件){循環(huán)操作}
特點:先判斷在執(zhí)行
do{循環(huán)操作}while(循環(huán)條件)
特點:先執(zhí)行在判斷
for(初始化變量并賦值;循環(huán)條件;循環(huán)迭代){
//循環(huán)操作
}
特點:循環(huán)次數(shù)固定的情況下。
四、break:
1.在switch中:退出case語句
2.在循環(huán)中:結束循環(huán)
五、continue:
結束當前循環(huán)繼續(xù)下次循環(huán)
六、foreach循環(huán):
特點:主要遍歷數(shù)組、集合或者字符串
語法:foreach(數(shù)據(jù)類型 變量名 in 數(shù)組(集合)){
//循環(huán)操作
}
eg:
String str =“我愛你中國”;
foreach(char s in str){
Console.WriteLine(s);
}
七、冒泡排序
口訣:n個數(shù)字來排序,兩兩相比小靠前,外層循環(huán)n-1,內層循環(huán)n-1-i。
eg: public static void TestMP() {
int[] num = {32,45,76,2,43,36 };
//將數(shù)組中的元素從小到大顯示出來
//外層循環(huán):比較的是多少輪 n-1
//內層循環(huán):比較的是每輪多少次 n-1-i
int temp = 0;
for (int i = 0; i < num.Length - 1;i++ ) {
for (int j = 0; j < num.Length - 1 - i;j++ ) {
if(num[j]>num[j+1]){
temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
}
}
}
Console.WriteLine(“從小到大排序結果為:”);
foreach(int n in num){
Console.WriteLine(n);
}
}
總結
- 上一篇: 4000元游戏电脑配置推荐?
- 下一篇: 深入C#中的String类