一個無聊的面試題

來源:互聯網
上載者:User

公司糟了災,年底了還要去找工作,真是流年不利啊。面試題啥的,向來是很反感的,有啥意義呢?哎~~,世道如此,只好把面經啥的又捧起來看了,煩啊。

 

題目很簡單了,就是列印下面這種樣式的字元,主要的邏輯很簡單,可是面經上的解答實在不給力啊,直接就main裡一個for就列印出來,這不是騙小孩麼,也不知道那時候買這個幹嘛,不過那會剛畢業,也差不多是個小屁孩了。往簡單了想,變化點有三個,一個是列印的行數,一個是列印到什麼位置,一個是列印的花紋,OO啥的不折騰了,就用C風格寫下算了。

 

列印的風格函數用回呼函數來隔離變化,比如上面的圖裡第一行是有星號,沒點號的。需求變化的話,可以變成從第一行開始就有點號,第二行有兩個點這樣依次。關於列印的位置,這裡就用c++流裡的基類函數ostream,ofstream因為是派生自它的,而<< 是虛函數。看代碼:

    typedef void (*PrintUnit) (int rowNum, ostream* out);     void PrintUintWithStyle1(int rowNum, ostream* out) {        //print star *        (*out)<<'*';        for (int i=0; i<rowNum; i++) {            (*out)<<'.';        }    }     void PrintUintWithStyle2(int rowNum, ostream* out) {        //print star *        (*out)<<'*';        for (int i=0; i<rowNum+1; i++) {            (*out)<<'.';        }    }     void PrintRows(int rows, PrintUnit fp, ostream* out) {        for(int i=0; i<10; i++) {            for(int k=0; k<i+1; k++) {                fp(i, out);            }            (*out)<<endl;        }    }     void Print10RowsWithStyle1ToStdout() {        PrintRows(10, PrintUintWithStyle1, &cout);    }     void Print10RowsWithStyle2ToFile() {        ofstream fout("1.txt");        PrintRows(10, PrintUintWithStyle2, &fout);    }     int main(int argc, char* argv[]){        Print10RowsWithStyle1ToStdout();        Print10RowsWithStyle2ToFile();         return 0;    } 

最後在螢幕上列印出:

在檔案裡列印出:

*.

*..*..

*...*...*...

*....*....*....*....

*.....*.....*.....*.....*.....

*......*......*......*......*......*......

*.......*.......*.......*.......*.......*.......*.......

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.