[問題] C語言初學觀念請益
開發平台(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
→
11/06 01:01,
2年前
, 1F
11/06 01:01, 1F
→
11/06 01:52,
2年前
, 2F
11/06 01:52, 2F
→
11/06 09:40,
2年前
, 3F
11/06 09:40, 3F
推
11/06 12:53,
2年前
, 4F
11/06 12:53, 4F
→
11/06 14:06,
2年前
, 5F
11/06 14:06, 5F
→
11/06 14:06,
2年前
, 6F
11/06 14:06, 6F
推
11/06 14:14,
2年前
, 7F
11/06 14:14, 7F
→
11/06 19:07,
2年前
, 8F
11/06 19:07, 8F
→
11/06 19:10,
2年前
, 9F
11/06 19:10, 9F
→
11/06 19:12,
2年前
, 10F
11/06 19:12, 10F
→
11/06 19:13,
2年前
, 11F
11/06 19:13, 11F
→
11/06 20:02,
2年前
, 12F
11/06 20:02, 12F
推
11/07 20:57,
2年前
, 13F
11/07 20:57, 13F
→
11/07 20:57,
2年前
, 14F
11/07 20:57, 14F
推
11/07 21:50,
2年前
, 15F
11/07 21:50, 15F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章