在C中查找数组中的最大值
我有几个问题。 我有一个包含这些信息的文本文件
x0,x1,y0,y1
142,310,0,959
299,467,0,959
456,639,0,959
628,796,0,959
首先,我想使用
<前><代码>c[1] = {142, 310, 0, 959} c[2] = {299, 467, 0, 959} c[3] = {456, 639, 0, 959} c[4] = {628, 796, 0, 959}fscanf
读取文本文件并仅将数字放入4个数组中,c1
,c2
、c3
和c4
跳过第一行。所以最终的结果就是然后,对于每个
c[1]
到c[4]
,我想找到最大整数并将其存储在 [x , y] 数据类型。例如,在c[1]
中,最大值将为max[1]
= [310, 959]。
有人可以帮忙吗?除了使用数组来解决这个问题之外,其他 C 解决方案也是受欢迎的。
在 matlab 中,代码为
fid = fopen('foo.txt','r');
c = textscan(fid,'%d%d%d%d','delimiter',',','headerlines',1);
fclose(fid);
这将简单地忽略第一行,然后将其余数字复制到 matlab 中的数组中。 我想把这段代码翻译成C语言。 非常感谢。
I have couple of questions.
I have a text file which contains these information
x0,x1,y0,y1
142,310,0,959
299,467,0,959
456,639,0,959
628,796,0,959
First, I want to read the text file using
fscanf
and get only the numbers into 4 arrays,c1
,c2
,c3
, andc4
by skipping the first line. So the final result will bec[1] = {142, 310, 0, 959} c[2] = {299, 467, 0, 959} c[3] = {456, 639, 0, 959} c[4] = {628, 796, 0, 959}
Then, for each
c[1]
toc[4]
, I want to find the maximum integer and store it in [x, y] datatype. So for example inc[1]
, the max will bemax[1]
= [310, 959].
Can anyone help? Other C solution other than using arrays to solve this problem is welcome as well.
In matlab, the code is
fid = fopen('foo.txt','r');
c = textscan(fid,'%d%d%d%d','delimiter',',','headerlines',1);
fclose(fid);
This will simply ignore the first line, then copy rest of numbers into arrays in matlab.
I would like to translate this code into C.
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然不能直接满足您的问题,但我提供了一个使用
struct
、std::istream
和std::vector
读取点的示例。这些比 fscanf 和数组更受青睐。Point
结构提供了更高的可读性和更多的多功能性,因为您可以使用Point
声明其他类:您可以使用
添加从文件读取的方法要点:
数组是一个问题,可能会导致严重的运行时错误,例如缓冲区溢出。优先使用
std::vector
、类或结构到数组。此外,由于使用了 std::istream,这些结构和类可以轻松地与 std::cin 和文件(std::ifstream >):
Although not satsifying your question directly, I have provided an example of reading points using a
struct
,std::istream
andstd::vector
. These are preferred overfscanf
and arrays.The
Point
structure provides more readability, and IMHO, more versatility because you can declare other classes using aPoint
:You can add methods for reading from a file using the
operator>>
for point:Arrays are a problem and can lead to nasty runtime errors such as buffer overruns. Perfer
std::vector
, classes or structures to arrays.Also, since
std::istream
is used, these structures and classes can be easily used withstd::cin
and files (std::ifstream
):以防万一你的
也意味着其他语言,解决这个问题的Python代码将是这样的
,结果将是
Just in case your
also means other language, Python code to solve this problem will be like this
and the result will be