1.保留几位小数
#include <iostream>
#include <iomanip> //必须包含这个头文件
using namespace std;
void main( )
{ double a =3.141596;
cout<<fixed<<setprecision(3)<<a<<endl; //输出小数点后3位
2. 使用了未初始化的局部变量
Point* p ;//EORROR 使用了未初始化变量
/*******************************Correct*****************************************/
Point* p = new Point[n];//分配内存以存储变量
Right-Code:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
class Point {
double x, y;
public:
Point() { x = 0; y = 0; cout << "Constructor." << endl; }
Point(double x_value, double y_value) {
x = x_value; y = y_value;
}
double getx() { return x; }
double gety() { return y; }
void setx(double x1) { x = x1; }
void sety(double y1) { y = y1; }
void setxy(double x1, double y1) {
x = x1; y = y1;
}
double getdistance( const Point& p) {
return sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y));
}
~Point() { cout << "Distructor." << endl; }
};
int main() {
int t;
int x, y ,n,beindex=0,foreindex=0;
cin >> t;
while (t--) {
cin >> n;
//double* dis = new double[n * (n - 1) / 2];//分配内存以存储距离
Point* p = new Point[n];//分配内存以存储点
int i=0,j=0,z=0;
double maxdistance =0,h=0;
for ( i = 0; i < n; i++) {
cin >> x >> y;
p[i].setxy(x, y);
}
for (z = 0; z < n; z++) {
for (j = z + 1; j < n; j++) {
h = p[z].getdistance(p[j]);
if (h > maxdistance) {
beindex = z;
foreindex = j;
maxdistance = h;
}
}
}
cout << "The longeset distance is " << fixed << setprecision(2) << maxdistance << ",between p[" << beindex << "] and p[" << foreindex << "]." << endl;
//delete[]dis;//释放内存
delete[]p;//释放内存
}
return 0;
}