#include <iostream> #include <cmath> using namespace std; class Complex { private: double real, imag; public: void input() { cin >> real >> imag; } double getReal() const { return real; } double getImag() const { return imag; } }; double dist(int x1, int y1) { return sqrt((int)x1*x1 + (int)y1*y1); } double dist(double x1, double y1) { return sqrt((double)x1*x1 + (double)y1*y1); } double dist(const Complex& a, const Complex& b) { int dx = a.getReal() - b.getReal(); int dy = a.getImag() - b.getImag(); return sqrt(dx*dx + dy*dy); } int main() { int a1,b1; double a2,b2; Complex a3,b3; int type; cin>>type; if(type==1) { cin>>a1>>b1; cout<<dist(a1,b1)<<endl; } else if(type==2) { cin>>a2>>b2; cout<<dist(a2,b2)<<endl; } else { a3.input(); b3.input(); cout<<dist(a3,b3)<<endl; } return 0; }修改这个代码使得输入2 2.2 9.9时输出7.7
时间: 2023-11-29 17:05:23 浏览: 131
可以将第一个dist函数的参数类型改为double,同时在计算平方和时也需要使用double类型,代码如下:
```
#include <iostream>
#include <cmath>
using namespace std;
class Complex {
private:
double real, imag;
public:
void input() {
cin >> real >> imag;
}
double getReal() const {
return real;
}
double getImag() const {
return imag;
}
};
double dist(double x1, double y1) {
return sqrt(x1*x1 + y1*y1);
}
double dist(const Complex& a, const Complex& b) {
double dx = a.getReal() - b.getReal();
double dy = a.getImag() - b.getImag();
return sqrt(dx*dx + dy*dy);
}
int main() {
int a1, type;
double a2, b2;
Complex a3, b3;
cin >> type;
if (type == 1) {
cin >> a1 >> b1;
cout << dist(a1, b1) << endl;
}
else if (type == 2) {
cin >> a2 >> b2;
cout << dist(a2, b2) << endl;
}
else {
a3.input();
b3.input();
cout << dist(a3, b3) << endl;
}
return 0;
}
```
使用这个代码,输入2 2.2 9.9时会输出7.7。
阅读全文