c++ - 查找一组数据中的最小数字

标签 c++

我有一组数据,格式如下:

a1 b1 c1 d1
a2 b2 c2 d2
...
an bn cn dn

我的目标是找到 c 列的值最小的行。

我做了以下事情:

const int limit=100000;
float Array[limit][4];

int main() {

  double a, b, c, d, smallest, ref1, ref2;

  ifstream in("data.dat");

  int idx=-1, point;

  while(!in.eof()) {

    idx++;
    in >> a >> b >> c >> d;

    Array[idx][0]=a; Array[idx][1]=b; Array[idx][2]=c; Array[idx][3]=d;

} \\end of while

in.close();


   int count=idx;

   for(int i=1; i<count; i++) {

        ref1= Array[0][2];
        ref2 = Array[i][2];

        if(ref2 < ref1) {ref1 = ref2; point=i;}  //I thought this will save the smallest value 

         smallest = ref1; point= i;

} \\end for


cout << "point" << Array[point][0] << Array[point][1] << .. etc.

return 0;

} 

但是,输出是数据中的最后一个点。 (在输入这个问题时,我意识到 ref1 在读取新行时将始终是 Array[0][2]。所以现在我完全迷路了!)

如何保存一个点作为引用点,以便与其余数据进行比较,每次与较小的点比较时,它的值都变小?

更新:我通过采用 ref1=Array[0][2] 解决了这个问题;跳出 for 循环。

最佳答案

你应该像我在循环外做的那样设置一个引用并更新最小的,顺便说一句,不要将 float 与 double 混合,但这是一个示例代码:

#include <iostream>
#include <fstream>

using namespace std;


const int limit=100000;
float Array[limit][4];

int main() {

  double a, b, c, d, smallest, ref1, ref2;

  ifstream in("data.dat");

  int idx=-1, point;

  while(!in.eof()) {

    idx++;
    in >> a >> b >> c >> d;

    Array[idx][0]=a;
    Array[idx][1]=b;
    Array[idx][2]=c;
    Array[idx][3]=d;
  } //end of while

  in.close();
  int i = 0;
  int count;
  smallest = Array[i][2];
  for( i=1; i<count; i++) {
    ref2 = Array[i][2];

    if(ref2 < smallest) {
      smallest = ref2;
      point=i;
    }
  }

  std::cout << "point" << Array[point][0] << " "
            << Array[point][1] << " "
            << Array[point][2] << " "
            << Array[point][3] << std::endl;

return 0;

} 

有数据文件

1 2 3 4
2 3 8 9
1 3 5 2
1 1 1 1
2 4 2 4
3 1 0 1

HTH

关于c++ - 查找一组数据中的最小数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11935645/

相关文章:

c++ - 为什么默认模板参数不适用于 using 声明?

C++ 在具有 O(n) 空间的数组中找到第一个非重复整数

c++ - FFmpeg:如何在从 RTSP 读取时控制控制台输出?

c++ - 如何在 C++11 中定义 SFINAE 和静态断言的约束

c++ - X3501 'main' : entrypoint not found when compiling DirectX11 . VS2015 中的 hlsl 着色器

c++ - std::regex 忽略正则表达式命令中的空格

c++ - 测量运行时间——不够精确

c++ - 为什么 vector 总是空的?

c++ - 从另一个 .cpp 文件的主体编译一个 .cpp 文件

c++ - 这行代码中的 `const char* yes[5]`代表什么?