作者how0919 (joke)
看板C_and_CPP
標題[問題] C語言初學觀念請益
時間Sat Nov 6 00:30:15 2021
開發平台(Platform): (Ex: Win10, Linux, ...)
Win10
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
<stdlib.h>
問題(Question):
將使用者輸入字串轉為指定大小的矩陣
(EX. 1.0,2.0;3.0,4.0; 則存為2*2矩陣
1,2,3;4,5,6; 則存為2*3矩陣)
餵入的資料(Input):
1.0,2.0;3.0,4.0;
預期的正確結果(Expected Output):
1.0 2.0
3.0 4.0
錯誤結果(Wrong Output):
無
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[1000] = {0} , m[10][10][10] = {0};
float M[10][10] = {0},constant = 0;
int column=0, row=0, element=0, counter1 = 0, counter2 = 0,counter3 = 0;
gets(input);
for ( int i = 0; i < sizeof(input); i++)
{
if (input[i] == ';')
{
counter1++;
counter2 = 0;
counter3 = 0;
element++;
continue;
}
else if (input[i] == ',')
{
counter2++;
counter3 = 0;
element++;
continue;
}
m[counter1][counter2][counter3]=input[i];
counter3++;
}
column = counter1;
row = element / column;
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
M[i][j] = atof(m[i][j]);
}
}
for (int i = 0; i < column; i++)
{
for (int j = 0; j < column ; j++)
{
if (j == 0)
{
printf("\n%.1f\t", M[i][j]);
}
else
{
printf("%.1f\t", M[i][j]);
}
}
}
return 0;
}
補充說明(Supplement):
菜雞我第一個碰的程式是PYTHON
在寫PYTHON的時候 很習慣用string跟array的觀點去看題目
最近學C學了一個月
還是很習慣硬用array去解題
前幾天碰到輸入兩矩陣相乘
發現光是輸入2個矩陣就花了快50行
雖然輸出結果是對的
但是感覺作法很笨 好像太依賴PYTHON string split的概念
想問一下寫C是不是應該用跟PYTHON不同的觀點切入解題
順便問一下我的寫法應該怎麼改善
(還不是很習慣指標的用法 不知道這題能不能用指標寫)
附上我看到這題第一時間想到的圖
https://imgur.com/a/6ioxHsb
(第一次在這個版發文 不知道排版會不會跑掉
如果跑掉了 這是我傳到github上的
https://reurl.cc/ARpNZe)
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.229.104.230 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1636129817.A.ACD.html
→ firejox: 用 sscanf 切或者用 strtok 切都行 11/06 01:01
→ how0919: 感謝f大 多學到一招了 11/06 09:40
推 stupid0319: scanf很雷,有些開源都禁止使用 11/06 12:53
→ how0919: 剛開始寫都用gets 後來老師說會有記憶體越界的問題 才改 11/06 14:06
→ how0919: 用scanf 的 11/06 14:06
→ firejox: scanf 只要了解運作跟缺點其實還可以用 11/06 19:07
→ ManOfSteel: 參考cppreference的網站,會比較知道scanf的性質 11/06 19:10
→ ManOfSteel: 手邊剛好有筆記QQ 11/06 19:13
→ how0919: 感謝各位大大 11/06 20:02
推 b0920075: scanf 沒弄好也有越界問題XD 沒有格式化字串的需求看 11/07 20:57
→ b0920075: 你要不要用 fgets 11/07 20:57
推 Schottky: 推薦用 fgets 取代 gets 11/07 21:50