【发布时间】:2015-03-01 18:20:12
【问题描述】:
我从文件中读取了一个 RGB 值的数据集,我正在尝试编写 K 表示算法,所以我需要在数据集中找到最接近三个数字(3 个值)的值,你们中的任何一个都可以帮助我吗向我展示如何做到这一点?
我是编程菜鸟,所以请对滥用行为轻描淡写:L
感谢您的宝贵时间
下面这段代码读入文件:
#include "stdafx.h"
#include <iostream>;
#include <fstream>;
#include <string>;
#include <cstdlib>;
using namespace std;
class rgb {
public:
int r;
int g;
int b;
};
int _tmain(int argc, _TCHAR* argv[])
{
char filename[2000];
ifstream infile;
infile.open("file.txt");
if (infile.fail()) {
cerr << "something went wrong :(" << endl;
system("pause");
exit(1);
}
rgb array[500];
cout << "reading in file: " << endl;
for (int i = 0; i < 500; i++)
{
infile >> array[i].r >> array[i].g >> array[i].b;
cout << "r: " << array[i].r << " ";
cout << "g: " << array[i].g << " ";
cout << "b: " << array[i].b << " " << endl;
}
然后这段代码在数据集中找到最接近质心一(value1)的值,但继续阅读,你会在底部看到我真正需要的东西,这段代码是一种练习,可能有更好的方法:L
int num = 180; // random value assigned at 180
int centroid1x;
int distance = 400;
for (int i = 0; i < 500; i++)
{
if (abs(num - array[i].r) <= distance)
{
distance = abs(num - array[i].r);
centroid1x = array[i].r;
}
cout << centroid1x << " " ;
}
cout << endl << endl;
int centroid1y;
distance = 400;
for (int i = 0; i < 500; i++)
{
if (abs(num - array[i].g) <= distance)
{
distance = abs(num - array[i].g);
centroid1y = array[i].g;
}
cout << centroid1y << " " ;
}
cout << endl << endl;
int centroid1z;
distance = 400;
for (int i = 0; i < 500; i++)
{
if (abs(num - array[i].b) <= distance)
{
distance = abs(num - array[i].b);
centroid1z = array[i].b;
}
cout << centroid1z << " " ;
}
cout << endl << endl;
cout << "The closest x axis of centroid one is: " << centroid1x << endl;
cout << "The closest y axis of centroid one is: " << centroid1y << endl;
cout << "The closest z axis of centroid one is: " << centroid1z << endl << endl;
cout << "The closest point to centroid one is " << centroid1x << "." << centroid1y << "." << centroid1z << endl;
system("pause");
return 0;
}
我需要的是让代码找到所有接近 180 的数字,所有接近 40 的数字和所有接近 100 的数字。
【问题讨论】:
-
你的代码有什么问题。您不需要在此处编写所有代码,而是针对您的问题提供SSCCE。
-
我想学习一种方法让程序找出数据集(文件)中哪些数字更接近180、40和100
-
是的,但是你有一个代码,有什么不工作的?你能找出没有按预期工作的问题部分吗?
-
啊我明白了,上面的代码只找到(一个值)最接近 180 的值,我需要找到所有接近 180 的值,所有接近 40 的值以及所有接近 100 的值。“文件”中有 500 个值。我需要更改程序,以便检查“文件”中的所有值并保存是否接近 180、100 或 40
-
恐怕你不是很清楚。您是否尝试将 RGB 值数组细分为数组,以便第一个数组中的值都“更接近”一个质心而不是所有其他质心? “更接近”对您意味着什么?您在寻找 RGB 空间中的空间距离吗?