找回密码
 立即注册
查看: 185|回复: 0

关于欧氏距离的c++实现(转)

[复制链接]

958

主题

6521

回帖

7479

积分

百家姓状元

积分
7479
发表于 2009-8-24 17:34:08 | 显示全部楼层 |阅读模式


一个朋友毕业设计,需要用到一个简单的欧氏距离公式计算的工具,于是帮忙用C  写了一个。源码如下:
#include
#include
#include
#include
using namespace std;
int main()
{
//定义新旧两个矩阵
float oldoshi[5][3];
float newoshi[5][5];
//从键盘输入25*3的旧矩阵
cout>oldoshi[k];
}
}
//输出显示以便确认输入是否正确
cout<<"\nThe 5*3 matrix that you just entered:\n";
for(int m=0;m<=4;  m)
{
for(int n=0;n<=2;  n)
{
cout<<oldoshi[m][n]<<" ";
}
cout<<"\n";//一行输出三个元素
}
//从oldoshi矩阵中取出数据根据欧式距离公式生成新25*25矩阵
for(int r=0;r<=4;  r)//25行
{
//float newelem=0;
for(int c=0;c<=4;  c)//25列
{ float
newelem=0; //此句不能放别到的位置
for(int t=0;t<=2;  t)
{
newelem =(oldoshi[r][t]-oldoshi[c][t])*(oldoshi[r][t]-oldoshi[c][t]);

}

newoshi[r][c]=sqrt(newelem);//计算元素D(i,j)的值

}
}
//显示所得的25*25新矩阵
cout<<"\nThe 5*5 matrix that you want:\n";
for(int ni=0;ni<=4;  ni)
{
for(int nj=0;nj<=4;  nj)
{
cout<<newoshi[ni][nj]<<" ";
}
cout<<"\n";//一行输出5个元素
}
//保存结果到一个文件中
ofstream
outfile("Result.txt");//以输出模式打开文件,文件存在则覆盖,不存在则新建。

if (!outfile)
//打开文件失败
cerr<<"\nFile open failed!\n";
else
{
for(int ni=0;ni<=4;  ni)
{
for(int
nj=0;nj<=4;  nj)
{
outfile<<newoshi[ni][nj]<<"
";
}
outfile<<"\n";
}
}
//使得在windows环境运行时,窗口不一闪而过
cout<<"\nOops!Good job!\n"
<<"You also can see the result by opening
Result.txt in the same directory.\n"
<<"Now,Please press any key to
abort...\n";
getch();//获取一个字符但不在屏幕上回显 getche()则回显
//程序结束
return 0;
}
计算结果应该是一个对角线为0的对称矩阵。



您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|华人百家姓论坛

GMT+8, 2026-7-11 19:40 , Processed in 0.036440 second(s), 19 queries .

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表