Re: [問題] 九九乘法表的分隔線
※ 引述《shile775 (笑看人生)》之銘言:
(恕刪)
我的概念是這樣, 將每一個要顯示的元件稱為Cell, 依Cell顯示的
內容, 可分為兩種:
1. Numeric Cell : 顯示數字
2. Text Cell : 顯示字串
原表每種Cell的分布情形如下:
| 1 2 3 4 5 6 7 8 9
-- - -- -- - -- - -- - -- - -- - -- - -- - -- --
1 | 1 2 3 4 5 6 7 8 9
2 | 2 4 6 8 10 12 14 16 18
3 | 3 6 9 12 15 18 21 24 27
4 | 4 8 12 16 20 24 28 32 36
(以下略...)
Text Cell可分為 : 、 、--、-、| 5種
Numeric Cell內容皆為數字, 寬度至多為2, 有向左/右對齊兩種
我的 struct 定義如下:
struct Cell
{
union Content
{
char text[2 + 1];
unsigned value;
}content;
void (*Print)( struct Cell const*, FILE* );
};
舉個產生Cell的例子:
void PrintText( struct Cell const *this,
FILE *stream )
{
fprintf( stream, "%s", this->content.text );
}
struct Cell * MakeTextCell( char const *text )
{
struct Cell *cell = calloc( 1, sizeof(struct Cell) );
strncpy( cell->content.text, text, 2 );
cell->Print = &PrintText;
return cell;
}
然後創建一個11×20的Cell*陣列, 再初始化它:
struct Cell *table[ 11 ][ 19 ];
// 填入 Text Cell
for( size_t col = 4; col < 19; col += 2 )
table[ 0 ][ col ] = MakeTextCell( " " );
for( size_t row = 2; row < 11; ++row )
for( size_t col = 4; col < 19; col += 2 )
table[ row ][ col ] = MakeTextCell( " " );
// 填入 Text Cell |
table[ 0 ][ 1 ] = MakeTextCell( "|" );
for( size_t row = 2; row < 11; ++row )
table[ row ][ 1 ] = MakeTextCell( "|" );
// other works...
完整程式碼: http://codepad.org/MiXq3o1U
這樣對我來說比較直覺啦, 一些魔數都可以用巨集來取代, 要客製化
某區塊也比較容易, 只填好部份表格也可以馬上測試.
進階一點指標還可以共用記憶體, 不過這樣刪除就會比較麻煩, 先不
做了.
--
★ ★ ★ ★
★ ★ ★ ███ ███ █ █▌█ ██◣ ███ ▋▋█ ★ ★ ★
█▂█ █▃█ █ ███ █▆█ █▄█ ███
★ ★ █ ◣ █ █ █ ▋██ █▆◤ ███ ███ ★ ★
Kim Jae Kyung Koh Woo Ri Cho Hyun Young Kim Ji Sook
φwindyhorse No Eul Oh Seung A Jung Yoon Hye
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.121.197.115
推
08/03 01:45, , 1F
08/03 01:45, 1F
推
08/03 01:50, , 2F
08/03 01:50, 2F
推
08/03 01:56, , 3F
08/03 01:56, 3F
推
08/03 02:35, , 4F
08/03 02:35, 4F
推
08/03 04:05, , 5F
08/03 04:05, 5F
推
08/03 04:09, , 6F
08/03 04:09, 6F
gcc 4.5.0 with options : -std=c99 -ftrapv -pedantic -Wall
推
08/03 04:30, , 7F
08/03 04:30, 7F
推
08/03 10:08, , 8F
08/03 10:08, 8F
推
08/03 15:41, , 9F
08/03 15:41, 9F
雖然可以把字串的長度限制增大, 然後判斷:
if( cell != NULL )
cell->Print( cell, stdout );
這樣即使第 1 列只有一個 TextCell, 也是可以正常運作; 不過我還
是喜歡作比較整齊的分割, 所以對付這樣較沒規律的分布, 程式碼會
多一些: http://codepad.org/JzWRenlS
再者是加上 Modifiers 對少量例外的 TextCell作修改, 也可以減少
很多碼.
※ 編輯: loveme00835 來自: 140.121.197.115 (08/03 16:37)
討論串 (同標題文章)
完整討論串 (本文為第 3 之 3 篇):
2
12
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章