作者:
how0919 (joke)
2021-11-06 00:30:15開發平台(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)