網頁

2021年5月24日 星期一

R:COVID-19 疫情統計(2.繪圖)

這篇我講解一下如將統計資料做量化的圖表比較分析這樣比較有助於理解

(每日確診數比較:台灣,新加坡,南韓,中國大陸)

上一篇有提到如何將全球COVID-19統計資料抓取下來並存在data farm,例如我取出了台灣,
新加坡,南韓,中國大陸的4個國家最近365天的資料,可以用 tail(data) 來看最近的6筆也就是近6天的統計資料。

台灣在5/22 每日確診數達高峰 723例

新加坡維持每日30~40例

南韓每日約500~600多例

中國大陸10~20幾例

有了這些data frame 就可以用圖表方式來呈現要表示的資料,如果我要比較這4個國家的死亡率(Mortality_Rate)程式如下:

ggplot(taiwan.df, aes(dates, mortality_rate)) +
      geom_line(aes(color="Taiwan")) +
      geom_line(data=singapore.df, aes(color="Singapore")) +
      geom_line(data=korea.df, aes(color="Korea")) +
      geom_line(data=china.df, aes(color="China")) +
      guides(colour = guide_legend("Country")) +
      ggtitle('Mortality Rate Taiwan vs Singapore vs Korea vs China') +
      xlab('') +
      ylab('')

輸出:(新加坡死亡率很低)

(死亡率比較圖)


如果要比較總確診數程式如下:(Y軸我除以1000以K為單位)

ggplot(taiwan.df, aes(dates, cases/10^3)) +
      geom_line(aes(color="Taiwan")) +
      geom_line(data=singapore.df, aes(color="Singapore")) +
      geom_line(data=korea.df, aes(color="Korea")) +
      geom_line(data=china.df, aes(color="China")) +
      guides(colour = guide_legend("Country")) +
      ggtitle('Total Case Taiwan vs Singapore vs Korea vs China') +
      xlab('') +
      ylab('(K)')

輸出:(可以看到韓國確診數非常陡峭)

(總確診數比較圖)

如果比較每日確診數程式如下:

#Daily Case
ggplot(taiwan.df, aes(dates, daily)) +
    geom_line(aes(color="Taiwan")) +
    geom_line(data=singapore.df, aes(color="Singapore")) +
    geom_line(data=korea.df, aes(color="Korea")) +
    geom_line(data=china.df, aes(color="China")) +
    guides(colour = guide_legend("Country")) +
    ggtitle('Daily Case Taiwan vs Singapore vs Korea va China') +
    xlab('') +
    ylab('')

輸出:

(台灣在五月有很明顯的上升趨勢,韓國在2021/1月高峰後有下降,4月後明顯有增加趨勢,新加坡在2020/8後控制得很不錯)

 

(每日確診數比較圖)

2021年5月23日 星期日

R:COVID-19 疫情統計

約翰·霍普金斯大學的Github 有分享了全球 COVID-19 疫情的統計資料,點選開啟連結,

time_series_covid19_confirmed_global.csv
time_series_covid19_deaths_global.csv
time_series_covid19_recovered_global.csv
這3個檔案分別是全球確診數,死亡人數,復原人數統計

 

將這3個csv檔爬下來後用R的資料篩選,發現其中 5/22/2021台灣的確診數是723例,
並不是指揮中心公布的321例。

R的程式在此,有興趣的人可以參考: 

https://ideone.com/kw4Heg

如果不會寫程式其中網頁也有提供了查詢各個地區國家的疫情統計。

COVID-19 Dashboard


library(tidyverse)
library(ggplot2)
library(cowplot)
library(patchwork)
path <- "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/"
confirm_file <- "time_series_covid19_confirmed_global.csv"
deaths_file <- "time_series_covid19_deaths_global.csv"
recovered_file <- "time_series_covid19_recovered_global.csv"

confirmed_df <- read_csv(paste0(path, confirm_file))
deaths_df <- read_csv(paste0(path, deaths_file))
recovered_df <- read_csv(paste0(path, recovered_file))

sd <- length(confirmed_df) - 21  # start date
ed <- length((confirmed_df))     # end date
dates <- colnames(confirmed_df[, sd:ed])
dates <- as.Date(dates,format = "%m/%d/%y")
dates <- as.POSIXct(dates,tz = "GMT")
getCountrydata <- function(Country,
                           dates = dates,
                           confirmed_df = confirmed_df,
                           deaths_df = deaths_df,
                           recovered_df = recovered_df,
                           sd = sd, ed = ed) {
  if (Country == "all") {
    cases <- confirmed_df %>%
      #select(-(1:400)) %>%
      select(sd:ed) %>%
      colSums()
    death <- deaths_df %>%
      #select(-(1:400)) %>%
      select(sd:ed) %>%
      colSums()
    recovered <- recovered_df %>%
      #select(-(1:400)) %>%
      select(sd:ed) %>%
      colSums()
  }
  else {
    Country <- enquo(Country)
    cases <- confirmed_df %>%
      filter(`Country/Region` == !! Country) %>%
      #select(-(1:400)) %>%
      select(sd:ed) %>%
      colSums()
    death <- deaths_df %>%
      filter(`Country/Region` == !! Country) %>%
      #select(-(1:400)) %>%
      select(sd:ed) %>%
      colSums()
    recovered <- recovered_df %>%
      filter(`Country/Region` == !! Country) %>%
      #select(-(1:400)) %>%
      select(sd:ed) %>%
      colSums()
  }
  res.df <- tibble(dates,
                   cases = cases,
                   death = death,
                   recovery = recovered,
                   mortality_rate = death/cases,
                   recovery_rate = recovery/cases)
  return(res.df)
}
world.df <- getCountrydata(Country = "all",
                           dates = dates,
                           confirmed_df = confirmed_df,
                           deaths_df = deaths_df,
                           recovered_df = recovered_df, sd, ed)
#Taiwan
taiwan.df <- getCountrydata(Country = "Taiwan*",
                            dates = dates,
                            confirmed_df = confirmed_df,
                            deaths_df = deaths_df,
                            recovered_df = recovered_df, sd, ed)

tmp.cases.plot <- function(df.plot, Country) {
  df.plot %>%
    mutate(cases_k = cases) %>%
    ggplot( aes(x=dates, y=cases_k)) +
    geom_line(color="#69b3a2") +
    geom_point(color="#69b3a2", size=1) +
    scale_x_datetime(breaks = world.df$dates,
                     date_labels = '%m/%d')+
    ggtitle(paste0(Country," Evolution of COVID-19 cases")) +
    ylab("cases") +
    theme_cowplot() +
    theme(axis.text.x = element_text(size = 10,
                                     vjust = 0.5,
                                     hjust = 0.5,
                                     angle = 90))
}

tmp.deaths.plot <- function(df.plot, Country) {
  df.plot %>%
    ggplot( aes(x=dates, y=mortality_rate)) +
    geom_line(color="#69b3a2") +
    geom_point(color="#69b3a2", size=1) +
    scale_x_datetime(breaks = world.df$dates,
                     date_labels = '%m/%d')+
    ggtitle(paste0(Country," Evolution of COVID-19 death rates")) +
    ylab("Mortality rates(Death/Cases)") +
    theme_cowplot()+
    theme(axis.text.x = element_text(size = 10,
                                     vjust = 0.5,
                                     hjust = 0.5,
                                     angle = 90))
}
tmp.recover.plot <- function(df.plot, Country) {
  df.plot %>%
    ggplot( aes(x=dates, y=recovery_rate)) +
    geom_line(color="#69b3a2") +
    geom_point(color="#69b3a2", size=1) +
    scale_x_datetime(breaks = world.df$dates,
                     date_labels = '%m/%d') +
    scale_y_continuous(breaks=seq(0,1,0.2),limits = c(0,1)) +
    ggtitle(paste0(Country," Evolution of COVID-19 recovery rates")) +
    ylab("Recovery rates(Recovery/Cases)") +
    theme_cowplot()+
    theme(axis.text.x = element_text(size = 10,
                                     vjust = 0.5,
                                     hjust = 0.5,
                                     angle = 90))
}
#----------
sd <- length(confirmed_df) - 22; sd
ed <- sd; ed
dates <- colnames(confirmed_df[, sd:ed])
df <- getCountrydata(Country = "Taiwan*",
                     dates = dates,
                     confirmed_df = confirmed_df,
                     deaths_df = deaths_df,
                     recovered_df = recovered_df, sd, ed)
first_data <- df$cases[[1]] ; first_data
taiwan.df['daily'] <- NA; taiwan.df
for(i in 1:nrow(taiwan.df)) {
  if(i == 1)
    taiwan.df$daily[i] <- taiwan.df$cases[i]- first_data
  else
    taiwan.df$daily[i] <- taiwan.df$cases[i]- taiwan.df$cases[i - 1]
}; tail(taiwan.df, 10)

tmp.daily.plot <- function(df.plot, Country) {
  df.plot %>%
    mutate(daily = daily) %>%
    ggplot(aes(x = dates, y = daily)) +
    geom_line(color="#69b3a2") +
    geom_point(color="red", size=1) +
    scale_x_datetime(breaks = world.df$dates, date_labels = '%m/%d')+
    ggtitle(paste0(Country," Evolution of COVID-19 daily")) +
    ylab("daily") +
    theme_cowplot() +
    theme(axis.text.x = element_text(size = 10,
                                     vjust = 0.5,
                                     hjust = 0.5,
                                     angle = 90))
}
pic1 <- tmp.daily.plot(df.plot = taiwan.df, Country = "Taiwan"); pic1
pic2 <- tmp.cases.plot(df.plot = taiwan.df, Country = "Taiwan"); pic2
pic3 <- tmp.deaths.plot(df.plot = taiwan.df, Country = "Taiwan"); pic3
pic4 <- tmp.recover.plot(df.plot = taiwan.df, Country = "Taiwan"); pic4
pic1 + pic2 + pic3 + pic4 + plot_layout(ncol = 2)

輸出:



2021年5月19日 星期三

如何建立實聯制Google表單

 1.將COVID-19 防疫實聯制建立副本到自己的雲端硬碟

將Google試算表「COVID-19防疫實聯制措施」建立副本到你自己的雲端硬碟

2.點選【建立副本】

 3.此時畫面會出現: 上方會有副本字樣,雲端硬碟也會有此檔案


 4.請點選執行「創用CC授權(姓名標示)」這項功能,目的是在首次執行客製功能前會自動跳出要求你完成授權同意程序。


5.會虛線需要授權提示,按下【繼續】

6.選擇你的【帳號】:

7.點選【進階】

 8.點選【前往「COVID-19防疫實聯制措施」(不安全)】

9.點選【允許】上述條款

10. 此時再點選「創用CC授權(姓名標示)」這項功能,右下角會出現下圖的訊息就表示授權成功


 11.下拉選單【COVID-19防疫實聯制功能】,選擇【建立掃瞄表單網址QRcode】

右下角出現【已建立表單網址QRcode文件】表示QRcode已經建立


 12.到我的雲端硬碟查看會有一個COVID-19防疫實聯制措施(列印QRcode)檔案

13.點選開啟檔案就可看到QRcode


14.如果你是店家可以使用「COVID-19防疫實聯制措施之連鎖企業版」

15.例如:分店號碼1234


產生的QRcode


 16.用QRcode APP掃描後填寫表單資料,在雲端硬碟的檔案即可看到掃描的資料。


2021年3月28日 星期日

C 語言新手十誡

C 語言新手十誡(The Ten Commandments for Newbie C Programmers)

  1. 本篇旨在提醒新手,避免初學常犯的錯誤(其實老手也常犯:-Q)。但不能取代完整的學習,請自己好好研讀一兩本 C 語言的好書,並多多實作練習。
  2. 強烈建議新手先看過此文再發問,你的問題極可能此文已經提出並解答了。
  3. 以下所舉的錯誤例子如果在你的電腦上印出和正確例子相同的結果,那只是不足為恃的一時僥倖。
  4. 不守十誡者,輕則執行結果的輸出數據錯誤,或是程式當掉,重則引爆核彈、毀滅地球(如果你的 C 程式是用來控制核彈發射器的話)。

  • 1. 不可以使用尚未給予適當初值的變數
  • 2. 不能存取超過陣列既定範圍的空間
  • 3. 不可以提取不知指向何方的指標
  • 4. 不要試圖用 char* 去更改一個"字串常數"
  • 5. 不能在函式中回傳一個指向區域性自動變數的指標
  • 6. 不可以只做 malloc(), 而不做相應的 free()
  • 7. 在數值運算、賦值或比較中不可以隨意混用不同型別的數值
  • 8. 在一個運算式中,不能對一個基本型態的變數修改其值超過一次以上
  • 9. 在 Macro 定義中, 務必為它的參數個別加上括號
  • A(10). 不可以在 stack 設置過大的變數
  • B(11). 使用浮點數精確度造成的誤差問題
  • C(12). 不要猜想二維陣列可以用 pointer to pointer 來傳遞
  • D(13). 函式內 new 出來的空間記得要讓主程式的指標接住

01. 你不可以使用尚未給予適當初值的變數
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    錯誤例子:
    int accumulate(int max)    /* 從 1 累加到 max,傳回結果 */
    {
        int sum;    /* 未給予初值的區域變數,其內容值是垃圾 */
        int num;
        for (num = 1; num <= max; num++) {  sum += num;  }
        return sum;
    }

    正確例子:
    int accumulate(int max)
    {
        int sum = 0;    /* 正確的賦予適當的初值 */
        int num;
        for (num = 1; num <= max; num++) {  sum += num;  }
        return sum;
    }

02. 你不可以存取超過陣列既定範圍的空間
1
2
3
4
5
6
7
8
9
    錯誤例子:
    int str[5];
    int i;
    for (i = 0 ; i <= 5 ; i++) str[i] = i;

    正確例子:
    int str[5];
    int i;
    for (i = 0; i < 5; i++) str[i] = i;
  • 說明:宣告陣列時,所給的陣列元素個數值如果是 N, 那麼我們在後面
  • 透過 [索引值] 存取其元素時,所能使用的索引值範圍是從 0 到 N-1
  • C/C++ 為了執行效率,並不會自動檢查陣列索引值是否超過陣列邊界,我們要自己來確保不會越界。一旦越界,操作的不再是合法的空間,將導致無法預期的後果。

03. 你不可以提取(dereference)不知指向何方的指標(包含 null 指標)。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
    錯誤例子:
    char *pc1;      /* 未給予初值,不知指向何方 */
    char *pc2 = 0;  /* pc2 起始化為 null pointer */
    *pc1 = 'a';     /* 將 'a' 寫到不知何方,錯誤 */
    *pc2 = 'b';     /* 將 'b' 寫到「位址0」,錯誤 */

    正確例子:
    char c;          /* c 的內容尚未起始化 */
    char *pc1 = &c;  /* pc1 指向字元變數 c */
    *pc1 = 'a';      /* c 的內容變為 'a' */

    /* 動態分配 10 個 char(其值未定),並將第一個char的位址賦值給 pc2 */
    char *pc2 = (char *) malloc(10);
    pc2[0] = 'b';    /* 動態配置來的第 0 個字元,內容變為 'b'
    free(pc2);
  • 說明:指標變數必需先指向某個可以合法操作的空間,才能進行操作。
    ( 使用者記得要檢查 malloc 回傳是否為 NULL,礙於篇幅本文假定使用上皆合法,也有正確歸還記憶體 )
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    錯誤例子:
    char *name;   /* name 尚未指向有效的空間 */
    printf("Your name, please: ");
    gets(name);   /* 您確定要寫入的那塊空間合法嗎??? */
    printf("Hello, %s\n", name);

    正確例子:
    /* 如果編譯期就能決定字串的最大空間,那就不要宣告成 char* 改用 char[] */

    char name[21];   /* 可讀入字串最長 20 個字元,保留一格空間放 '\0' */
    printf("Your name, please: ");
    gets(name);
    printf("Hello, %s\n", name);
正確例子(2):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
    /* 若是在執行時期才能決定字串的最大空間,則需利用 malloc() 函式來動態分配空間 */

    size_t length;
    char *name;
    printf("請輸入字串的最大長度(含null字元): ");
    scanf("%u", &length);

    name = (char *)malloc(length);
    printf("Your name, please: ");
    scanf("%s", name);
    printf("Hello, %s\n", name);

    /* 最後記得 free() 掉 malloc() 所分配的空間 */
    free(name);

04. 你不可以試圖用 char* 去更改一個"字串常數"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    錯誤例子:
    char* pc = "john";   /* pc 現在指著一個字串常數 */
    *pc = 'J';   /* 但是 pc 沒有權利去更改這個常數! */



    正確例子:
    char pc[] = "john";  /* pc 現在是個合法的陣列,裡面住著字串 john */
                         /* 也就是 pc[0]='j', pc[1]='o', pc[2]='h',                                              pc[3]='n', pc[4]='\0'  */
    *pc = 'J';
    pc[2] = 'H';
  • 說明:字串常數的內容是"唯讀"的。您有使用權,但是沒有更改的權利。
  • 若您希望使用可以更改的字串,那您應該將其放在合法空間
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
    錯誤例子:
    char *s1 = "Hello, ";
    char *s2 = "world!";
    /* strcat() 不會另行配置空間,只會將資料附加到 s1 所指唯讀字串的後面,       造成寫入到程式無權碰觸的記憶體空間 */
    strcat(s1, s2);



    正確例子(2):
    /* s1 宣告成陣列,並保留足夠空間存放後續要附加的內容 */
    char s1[20] = "Hello, ";
    char *s2 = "world!";
    /* 因為 strcat() 的返回值等於第一個參數值,所以 s3 就不需要了 */
    strcat(s1, s2);

05. 你不可以在函式中回傳一個指向區域性自動變數的指標。否則,會得到垃圾值
[感謝 gocpp 網友提供程式例子]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
    錯誤例子:
    char *getstr(char *name)
    {
        char buf[30] = "hello, "; /*將字串常數"hello, "的內容複製到buf陣列*/
        strcat(buf, name);
        return buf;
    }

    說明:區域性自動變數,將會在離開該區域時(本例中就是從getstr函式返回時)
    被消滅,因此呼叫端得到的指標所指的字串內容就失效了。

    正確例子:
    void getstr(char buf[], int buflen, char const *name)
    {
        char const s[] = "hello, ";
        strcpy(buf, s);
        strcat(buf, name);
    }

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    正確例子:
    int* foo()
    {
        int* pInteger = (int*) malloc( 10*sizeof(int) );
        return pInteger;
    }

    int main()
    {
        int* pFromfoo = foo();
    }
  • 說明:上例雖然回傳了函式中的指標,但由於指標內容所指的位址並非區域變數,
  • 而是用動態的方式抓取而得,換句話說這塊空間是長在 heap 而非 stack,
  • 又因 heap 空間並不會自動回收,因此這塊空間在離開函式後,依然有效
  • (但是這個例子可能會因為 programmer 的疏忽,忘記 free 而造成memory leak)
[針對字串操作,C++提供了更方便安全更直觀的 string class, 能用就盡量用]


1
2
3
4
5
6
7
8
9
    正確例子:

    #include <string>    /* 並非 #include <cstring> */
    using std::string;

    string getstr(string const &name)
    {
        return string("hello, ") += name;
    }

06. 你不可以只做 malloc(), 而不做相應的 free(). 否則會造成記憶體漏失
  • 但若不是用 malloc() 所得到的記憶體,則不可以 free()。
  • 已經 free()了所指記憶體的指標,在它指向另一塊有效的動態分配得來的空間之前,不可以再被 free(),也不可以提取(dereference)這個指標。
  • [C++] 你不可以只做 new, 而不做相應的 delete
  • 注:new 與 delete 對應,new[] 與 delete[] 對應,不可混用
    (切記,做了幾次 new,就必須做幾次 delete)
  • 小技巧: 可在 delete 之後將指標指到 0,由於 delete 本身會先做檢查,因此可以避免掉多次 delete 的錯誤
1
2
3
4
5
   正確例子:
   int *ptr = new int(99);
   delete ptr;
   ptr = NULL;
   delete ptr;   /* delete 只會處理指向非 NULL 的指標 */

07. 你不可以在數值運算、賦值或比較中隨意混用不同型別的數值,而不謹慎考
  • 慮數值型別轉換可能帶來的「意外驚喜」(錯愕)。必須隨時注意數值運算的結果,其範圍是否會超出變數的型別
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    錯誤例子:
    unsigned int sum = 2000000000 + 2000000000;  /* 超出 int 存放範圍 */
    unsigned int sum = (unsigned int) (2000000000 + 2000000000);
    double f = 10 / 3;


    正確例子:
    /* 全部都用 unsigned int, 注意數字後面的 u, 大寫 U 也成 */
    unsigned int sum = 2000000000u + 2000000000u;

    /* 或是用顯式的轉型 */
    unsigned int sum = (unsigned int) 2000000000 + 2000000000;

    double f = 10.0 / 3.0;


1
2
3
4
    錯誤例子:
    unsigned int a = 0;
    int b[10];
    for(int i = 9 ; i >= a ; i--) {  b[i] = 0;  }
  • 說明:由於 int 與 unsigned 共同運算的時候,會提升 int 為 unsigned,因此迴圈條件永遠滿足,與預期行為不符
1
2
3
4
5
6
    錯誤例子:                                 (感謝 sekya 網友提供)
    unsigned char a = 0x80;   /* no problem */
    char b = 0x80;    /* implementation-defined result */
    if( b == 0x80 ) {        /* 不一定恒真 */
        printf( "b ok\n" );
    }
  • 說明:語言並未規定 char 天生為 unsigned 或 signed,因此將 0x80 放入char 型態的變數,將會視各家編譯器不同作法而有不同結果

08. 你不可以在一個運算式(expression)中,對一個基本型態的變數修改其值超過一次以上。否則,將導致未定義的行為(undefined behavior)
1
2
3
4
5
6
7
8
    錯誤例子:
    int i = 7;
    int j = ++i + i++;

    正確例子:
    int i = 7;
    int j = ++i;
    j += i++;
  • 你也不可以在一個運算式(expression)中,對一個基本型態的變數修改其值,而且還在同一個式子的其他地方為了其他目的而存取該變數的值。(其他目的,是指不是為了計算這個變數的新值的目的)。否則,將導致未定義的行為。
1
2
    錯誤例子:
    x = x++;

1
 2
 3
 4
 5
 6
 7
 8
 9
10
    錯誤例子:
    int arr[5];
    int i = 0;
    arr[i] = i++;

    正確例子:
    int arr[5];
    int i = 0;
    arr[i] = i;
    i++;

1
2
3
4
5
6
7
8
    錯誤例子:
    int i = 10;
    cout << i << "==" << i++;

    正確例子:
    int i = 10;
    cout << i << "==";
    cout << i++;


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    錯誤例子:
    int Integer=10;
    printf( "%d %d %d", Integer++, Integer++, Integer++ );


    錯誤例子:
    void foo(int a, int b) { ... }
    int main() {
        int i=0;
        foo(i++, i++);
    }

  • 說明: C/C++ 並沒有強制規定參數會由哪個方向開始處理(不像Java是由左到右),因此可能會造成與預期不符的情況

09. 在 Macro 定義中, 務必為它的參數個別加上括號

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
    錯誤例子:
    #include <stdio.h>
    #define SQUARE(x)    (x * x)
    int main()
    {
        printf("%d\n", SQUARE(10-5));
        return 0;
    }

    正確例子:
    #include <stdio.h>
    #define SQUARE(x)    ((x) * (x))
    int main()
    {
        printf("%d\n", SQUARE(10-5));
        return 0;
    }
  • 說明:如果是用 C++, 請多多利用 inline function 來取代上述的 macro,以免除 macro 定義的種種危險性。如:
    inline int square(int x) { return x * x; }
  • macro 定義出的「偽函式」至少缺乏下列數項函式本有的能力:
    • (1) 無法進行參數型別的檢查。
    • (2) 無法遞迴呼叫。
    • (3) 無法用 & 加在 macro name 之前,取得函式位址。
    • (4) 呼叫時往往不能使用具有 side effect 的引數。例如:
1
2
3
4
5
6
7
8
    錯誤例子:                                      (感謝 yaca 網友提供)
    #define MACRO(x)     (((x) * (x)) - ((x) * (x)))
    int main()
    {
        int x = 3;
        printf("%d\n", MACRO(++x));
        return 0;
    }
    • 備註:副作用(side effect)
    • 表达式有两种功能:每个表达式都产生一个值( value ),同时可能包含副作用( side effect )。副作用是指改变了某些变量的值。
      • 1:20 //这个表达式的值是20;它没有副作用,因为它没有改变任何变量的值。
      • 2:x=5 // 这个表达式的值是5;它有一个副作用,因为它改变了变量x的值。
      • 3:x=y++ // 这个表达示有两个副作用,因为改变了两个变量的值。
      • 4:x=x++ // 这个表达式也有两个副作用,因为变量x的值发生了两次改变。

10. 不可在 stack 設置過大的變數,否則會造成 stack overflow
(感謝 VictorTom 版友幫忙)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    錯誤例子:
    int array[10000000];       // 僅舉例說明

   /* 說明:由於編譯器會自行決定 stack 的上限,某些預設是數 KB 或數十 KB
    當變數所需的空間過大時,很容易造成 stack overflow,程式亦隨之
    當掉,若真正需要如此大的空間,那麼建議配置在 heap 上,或是採用
    static / globla variable,亦或是改變編譯器的設定
    使用 heap 時,雖然整個 process 可用的空間是有限的,但採用動態抓取
    的方式,new 無法配置時會丟出 std::bad_alloc 例外,malloc 無法配置
    時會回傳 null,不會影響到正常使用下的程式功能    */
    正確例子:
    int *array = (int*) malloc( 10000000*sizeof(int) );
  • 說明:由於此時 stack 上只需配置一個 int* 的空間,可避免 stack overflow
  • 更多說明請參考精華區 z-10-13

11. 使用浮點數千萬要注意精確度所造成的誤差問題

根據 IEEE 754 的規範,又電腦中是用有限的二進位儲存數字,因此常有可
能因為精確度而造成誤差,例如加減乘除,等號大小判斷,分配律等數學上
常用到的操作,很有可能因此而出錯(不成立)

更詳細的說明可以參考精華區 z-8-11
或參考冼鏡光老師所發表的一文 "使用浮點數最最基本的觀念"
http://blog.dcview.com/article.php?a=VmgBZFE5AzI%3D

12. 不要猜想二維陣列可以用 pointer to pointer 來傳遞
(感謝 loveme00835 legnaleurc 版友的幫忙)

首先必須有個觀念,C 語言中陣列是無法直接拿來傳遞的!
不過這時候會有人跳出來反駁:
1
2
3
4
    void pass1DArray( int array[] );

    int a[10];
    pass1DArray( a );   /* 可以合法編譯,而且執行結果正確!! */
事實上,編譯器會這麼看待
1
2
3
4
    void pass1DArray( int *array );

    int a[10];
    pass1DArray( &a[0] );
  • 我們可以順便看出來,array 變數本身可以 decay 成記憶體起頭的位置
  • 因此我們可以 int *p = a; 這種方式,拿指標去接陣列。
  • 也因為上述的例子,許多人以為那二維陣列是不是也可以改成 int **
1
2
3
4
5
6
7
    錯誤例子:
    void pass2DArray( int **array );

    int a[5][10];
    pass2DArray( a );
    /* 這時候編譯器就會報錯啦 */
    /* expected ‘int **’ but argument is of type ‘int (*)[10]’*/

  • 在一維陣列中,指標的移動操作,會剛好覆蓋到陣列的範圍,例如,宣告了一個 a[10],那我可以把 a 當成指標來操作 *a 至 *(a+9)
  • 因此我們可以得到一個概念,在操作的時候,可以 decay 成指標來使用,也就是我可以把一個陣列當成一個指標來使用 (again, 陣列!=指標)
  • 但是多維陣列中,無法如此使用,事實上這也很直觀,試圖拿一個pointer to pointer to int 來操作一個 int 二維陣列,這是不合理的!
  • 儘管我們無法將二維陣列直接 decay 成兩個指標,但是我們可以換個角度想,二維陣列可以看成 "外層大的一維陣列,每一維內層各又包含著一維陣列"
  • 如果想通了這一點,我們可以仿造之前的規則,把外層大的一維陣列 decay 成指標,該指標指向內層的一維陣列
1
2
3
4
    void pass2DArray( int (*array) [10] );  // array 是個指標,指向 int [10]

    int a[5][10];
    pass2DArray( a );

  • 這時候就很好理解了,函數 pass2DArray 內的 array[0] 會代表什麼呢?答案是它代表著 a[0] 外層的那一維陣列,裡面包含著內層 [0]~[9],也因此 array[0][2] 就會對應到 a[0][2],array[4][9] 對應到 a[4][9]
  • 結論就是,只有最外層的那一維陣列可以 decay 成指標,其他維陣列都要明確的指出陣列大小,這樣多維陣列的傳遞就不會有問題了
  • 也因為剛剛的例子,我們可以清楚的知道在傳遞陣列時,實際行為是在傳遞指標,也因此如果我們想用 sizeof 來求得陣列元素個數,那是不可行的
1
2
3
4
    錯誤例子:
    void print1DArraySize( int* arr ) {
        printf("%u", sizeof(arr)/sizeof(arr[0])); /* sizeof(arr) 只是 */
    }      
  • 受此限制,我們必須手動傳入大小
1
    void print1DArraySize( int* arr, size_t arrSize );
  • 註:typedef unsigned int size_t 與平台無關的,表示0-MAXINT的無號整數
  • C++ 提供 reference 的機制,使得我們不需再這麼麻煩,可以直接傳遞陣列的 reference 給函數,大小也可以直接求出
1
2
3
4
    正確例子:
    void print1DArraySize( int (&array)[10] ) {    // 傳遞 reference
        cout << sizeof(array) / sizeof(int);   // 正確取得陣列元素個數
    }

13. 函式內 new 出來的空間記得要讓主程式的指標接住
  • 對指標不熟悉的使用者會以為以下的程式碼是符合預期的
1
2
3
4
5
6
7
8
    void newArray(int* local, int size) {
        local = (int*) malloc( size * sizeof(int) );
    }

    int main() {
        int* ptr;
        newArray(ptr, 10);
    }
  • 接著就會找了很久的 bug,最後仍然搞不懂為什麼 ptr 沒有指向剛剛拿到的合法空間,讓我們再回顧一次
  • 1. int* ptr;ptr 指向未知的空間
  • 2. 呼叫函式 newArray,ptr和local指向未知的空間
  • 3. malloc 取得合法空間ptr指向未知的空間 ,為local
  • 4. 離開函ptr 只向未知空間
  • 也許有人會想問,指標不是傳址嗎?精確來講,指標也是傳值,只不過該值是一個位址 (ex: 0xfefefefe)
    • local 接到了 ptr 指向的那個位置,接著函式內 local 要到了新的位置
    • 但是 ptr 指向的位置還是沒變的,因此離開函式後就好像事什麼都沒發生
      ( 嚴格說起來還發生了 memory leak )
  • 以下是一種解決辦法
1
2
3
4
5
6
7
8
    int* createNewArray(int size) {
        return (int*) malloc( size * sizeof(int) );
    }

    int main() {
        int* ptr;
        ptr = createNewArray(10);
    }
  • 改成這樣亦可 ( 為何用 int** 就可以?想想他會傳什麼過去給local )
1
2
3
4
5
6
7
8
    void createNewArray(int** local, int size) {
        *local = (int*) malloc( size * sizeof(int) );
    }

    int main() {
        int *ptr;
        createNewArray(&ptr, 10);
    }
  • 如果是 C++,別忘了可以善用 Reference
1
2
3
    void newArray(int*& local, int size) {
        local = new int[size];
    }

 

資料來源:

https://www.ptt.cc/bbs/C_and_CPP/M.1268491365.A.EF7.html


2021年3月15日 星期一

Unix System Programming (1092)-exer2

http://erdos.csie.ncnu.edu.tw/~klim/unix-p/usp-1092.html

exercise 2: probing argv[] and environ[]

    Write a program which prints the values of argc, argv[], and environ[]. Also their addresses are printed. Based on the printed information, you can figure out the memory layout of argc, argv[], and environ[].
For example:

$ ./a.out klim is not milk
 argc is 5
 argv[0]: ./a.out
 argv[1]: klim
 argv[2]: is
 argv[3]: not
 argv[4]: milk
 environ[0]: CPLUS_INCLUDE_PATH=/usr/lib64/qt/include
 environ[1]: NNTPSERVER=news.ncnu.edu.tw
 .......
 environ[33]: INFOPATH=/usr/info:/usr/share/texmf/info
 environ[34]: G_BROKEN_FILENAMES=1
 environ[35]: _=./a.out
 environ[36]: OLDPWD=/home/klim/course/usp-1092

 argc      is resided at 0x7ffdddad11fc
 argv      is resided at 0x7ffdddad11f0
 environ   is resided at 0x601040
 argv[]    is resided at 0x7ffdddad12f8
 environ[] is resided at 0x7ffdddad1328
 value of argv[ 0] is 0x7ffdddad24c3
 value of argv[ 1] is 0x7ffdddad24cb
 value of argv[ 2] is 0x7ffdddad24d0
 value of argv[ 3] is 0x7ffdddad24d3
 value of argv[ 4] is 0x7ffdddad24d7
 value of argv[ 5] is (nil)
 value of env [ 0] is 0x7ffdddad24dc
 value of env [ 1] is 0x7ffdddad2505
 value of env [ 2] is 0x7ffdddad2521
 ..........
 value of env [35] is 0x7ffdddad2fc4
 value of env [36] is 0x7ffdddad2fce
 $


    If there are too many environment strings to display, you can try to use ``env'' to get a cleaner environment. For example:

$ env -i A=1 hello=ohio ./a.out see you again
argc is 4
argv[0]: ./a.out
argv[1]: see
argv[2]: you
argv[3]: again
environ[0]: A=1
environ[1]: hello=ohio

argc      is resided at 0x7fff4b9083dc
argv      is resided at 0x7fff4b9083d0
environ   is resided at 0x601040
argv[]    is resided at 0x7fff4b9084d8
environ[] is resided at 0x7fff4b908500
value of argv[ 0] is 0x7fff4b908fcb
value of argv[ 1] is 0x7fff4b908fd3
value of argv[ 2] is 0x7fff4b908fd7
value of argv[ 3] is 0x7fff4b908fdb
value of argv[ 4] is (nil)
value of env [ 0] is 0x7fff4b908fe1
value of env [ 1] is 0x7fff4b908fe5
$

My program:
https://ideone.com/xz3wfv


2021年3月3日 星期三

Unix System Programming (1092)-exer1

exercise 1: a simple C program
  • Write a C program which reads strings from stdin and if a string is consisted of digits, it is treated as a number. Sum all the numbers and write sum to stdout.
  • The reading is terminated by end of file, that is, a ctrl-D.
  • The length of each string does not exceed 16.
  • You may assume the numbers and the sum can be handled with int.
  • For converting a string to a number, you may consult strtol().
  • For example:
    $ gcc ex1-sum-stdin.c 
    $ ./a.out 
    I have 1000
    You have 200
    I give you 50
    Now You have 250.   <---- ctrl-D pressed
    1250                <---- only 1000, 200, 50 are summed
    $ ./a.out 
    100 + 23 = 123
    $100 - 23 = 77.     <---- ctrl-D pressed
    269                 <---- 100, 23, 123, 23 are summed
     
    My program:
    https://ideone.com/V3fc8b
    https://ideone.com/hFVjyY
     

2021年1月30日 星期六

Automator:依檔案清單大量找檔案並拷貝

將程式流程製作成Automator,就不用在終端機下指令,對一班使用這來說會比較簡單。





1.於程式庫中選 工具程式 -> 執行AppleScript

on run {input, parameters}
    set theDialogText to "選擇 list 檔案"
    display dialog theDialogText
    --> Result: {button returned:"OK"}
    return input
end run

2.於程式庫中選 檔案和檔案夾 -> 要求Finder項目
類型選擇"檔案"






3.於程式庫中選 工具程式 -> 執行AppleScript

 on run {input, parameters}
    set theDialogText to "選擇 pic 目錄"
    display dialog theDialogText
    --> Result: {button returned:"OK"}
    return input
end run

4.於程式庫中選 檔案和檔案夾 -> 要求Finder項目
類型選擇"檔案夾"


5.於程式庫中選 工具程式 ->執行Shell工序指令
傳遞輸入選擇"作為引數使用",就是剛剛選擇檔案和目錄傳遞到此當輸入


執行畫面:



接著會執行script,然後將找到的檔案copy到桌面。