作者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://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1636129817.A.ACD.html
1F:→ firejox: 用 sscanf 切或者用 strtok 切都行 11/06 01:01
3F:→ how0919: 感谢f大 多学到一招了 11/06 09:40
4F:推 stupid0319: scanf很雷,有些开源都禁止使用 11/06 12:53
5F:→ how0919: 刚开始写都用gets 後来老师说会有记忆体越界的问题 才改 11/06 14:06
6F:→ how0919: 用scanf 的 11/06 14:06
8F:→ firejox: scanf 只要了解运作跟缺点其实还可以用 11/06 19:07
9F:→ ManOfSteel: 参考cppreference的网站,会比较知道scanf的性质 11/06 19:10
11F:→ ManOfSteel: 手边刚好有笔记QQ 11/06 19:13
12F:→ how0919: 感谢各位大大 11/06 20:02
13F:推 b0920075: scanf 没弄好也有越界问题XD 没有格式化字串的需求看 11/07 20:57
14F:→ b0920075: 你要不要用 fgets 11/07 20:57
15F:推 Schottky: 推荐用 fgets 取代 gets 11/07 21:50