c學習筆記--2變數型別與基本操作
阿新 • • 發佈:2018-12-12
好久之前的了,學習c語言的筆記。 依舊是老套路,從基礎的變數型別,到函式定義一步步學起
#include <stdio.h>
#include <string.h>
//c語言的變數型別與基本操作
void test2()
{
//數字型
int a = 45, b = 34;
float fa = 123;
double da = 32.5;
printf("元素 = %d\n",a);
//字元型
char str = "d";
char *str1 = "Hello";
char str2[] = "Another Hello";
printf("元素 = %s\n" , str2);
//指標型別
char *p = str2;
printf("元素 = %s\n", p);
//陣列一維
int n[10] = {1,2,3,4,5,6,7,8,9,10}; /* n 是一個包含 10 個整數的陣列 */
for (int j = 0; j < 10; j++)
{
printf("Element[%d] = %d\n", j, n[j]);
}
//數字二位陣列
int atwo[3][4] = { //完全初始化
{ 0, 1, 2, 3 } , /* 初始化索引號為 0 的行 */
{ 4, 5, 6, 7 } , /* 初始化索引號為 1 的行 */
{ 8, 9, 10, 11 } /* 初始化索引號為 2 的行 */
};
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
printf("元素 = %d \n", atwo[i][j]);
}
}
//其他二維陣列的初始化方式
int btwo[3][4] = { {0},{1,2},{1,2,3,4} }; //部分初始化
int ctwo[][4] = { { 0 },{ 1,2 },{ 1,2,3,4 } }; //分行部分初始化
//字串二維陣列的使用
char str3[][5] ={"1234","5678","9012" }; //字串陣列初始化
for (int j = 0; j < 3; j++)
{
printf("元素 = %s \n", &str3[j]);
}
//結構體
struct student
{
int age;
char name[20];
}st; //直接定義結構體變數 可以匿名(無結構體名字)
//先定義結構體 然後定義變數
struct teammember
{
int age;
char name[20];
};
struct teammember tm, tmarray[2], *tmp;
tm.age = 10;
//tm.name = "songyu";
//字串陣列賦值不能用“=” 除非直接初始化 name是陣列名,它是常量指標,其數值是不能修改的。
struct teammember ttemp = { 10,"1234" };
strcpy(tm.name, "songyu");
printf("struct name is: %s \n", tm.name);
//列舉型別
//列舉型別的實質是整數集合,列舉變數的引用同於整數變數的引用規則,並可以與整數型別
//的資料之間進行型別轉換而不發生資料丟失。
//如果自己不手動賦值,那麼系統自動從0開始
enum DAY
{
MON = 1, TUE=2, WED=3, THU=4, FRI=5, SAT=6, SUN=7
};
enum DAY day,tomorrow;
day = MON;
printf("enum tomorrow is: %d \n", day); //列舉的實質是數字
int tomorrows = (int)day + 1;
printf("enum tomorrow is: %d \n", tomorrows); //輸出的依舊是數字
//強制轉換為列舉
tomorrow = (enum DAY)tomorrows;
//printf("enum tomorrow is: %s \n", tomorrow); //輸出的依舊是數字
//列舉對應的字串根本在編譯後的程式中就沒有。只能再寫switch casep判斷輸出
//意思就是說 列舉就是方便我們進行判斷的 畢竟字串意義明顯 編譯之後字串就沒了
switch(tomorrow)
{
case MON:break;
case TUE:break;
case WED:break;
default:break;
}
gets(); //防止關閉
}