原题描叙:
请见http://blog.csdn.net/liuchang54/article/details/42341053;
代码如下:
#include <stdarg.h> #include <iostream> #include <math.h> #include <iomanip> using namespace std; int main() { double distance(int dime,double x1,double y1,double x2=0,double y2=0,double x3=0,double y3=0,double x4=0,double y4=0); int dime; double x1,y1,x2,y2,x3,y3,x4,y4,d; cout<<setiosflags(ios::fixed)<<setprecision(2); dime =1; cin>>x1>>y1; d = distance(dime,x1,y1); cout<<d<<endl; dime =2; cin>>x1>>y1>>x2>>y2; d = distance(dime,x1,y1,x2,y2); cout<<d<<endl; dime =3; cin>>x1>>y1>>x2>>y2>>x3>>y3; d = distance(dime,x1,y1,x2,y2,x3,y3); cout<<d<<endl; dime =4; cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4; d = distance(dime,x1,y1,x2,y2,x3,y3,x4,y4); cout<<d<<endl; return 0; } double distance(int dime,double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4) { double sum=0,d[5]; //str[dime]毛病多 int i=0; d[0]=x1-y1; d[1]=x2-y2; d[2]=x3-y3; d[3]=x4-y4; while (i<dime) { sum+=(d[i]*d[i]); i++; } sum=sqrt(sum); return sum; }
运行结果:
之前的代码:
现在的代码:
由于(应该是出题的老师出得有问题)这个题目在OJ上始终无法成功完成,我就把题目和自己写的代码发给了我们上课的贺老师,贺老师也没办法解决无法提交的问题,但他把我写的代码优化了一番,于是便有了这篇博文。之前并不是没有想过利用数组的界限,但因为当时觉得变量数目比较小,就没有多花心思去编写,,,现在想想,如果是20维怎么办?还有很长很长的路要走啊。
时间: 2024-10-23 15:08:33