Bài 2: Đa năng hóa toán tử
Đề bài: Nhập dữ lieu và các phương thức của số phức, nhap, in, tính modull và sử dung toán tử operator< để so sánh số phức; hàm main, nhập 1 day số phức sau đó in ra số phức nhỏ nhất.
Lời giải:
#include<iostream>
#include<math.h>
using namespace std;
class sophuc{
private:
int thuc;
int ao;
public:
sophuc(){
thuc=ao=0;
}
void input();
void output();
float modull(){
return sqrt(pow(thuc,2)+pow(ao,2));
}
int operator < (sophuc);
};
void sophuc::input(){
cout<<" nhap phan thuc = " ;
cin>>thuc;
cout<<" nhap phan ao = ";
cin>>ao;
}
void sophuc::output(){
if(ao<0) cout<<thuc<<"-"<<ao<<"i"<<endl;
else cout<<thuc<<"+"<<ao<<"I"<<endl;
}
int sophuc::operator < (sophuc x){
return (modull()<x.modull());
}
int main(){
int I,n,imin=0;
sophuc *a=new sophuc [n];
cout<<"nhap so phan tu cua mang n = ";
cin>>n;
// nhap mang so phuc
for(I=0;i<n;i++){
cout<<" nhap so phuc thu "<<I+1<<endl;
a[i].input();
}
// ham so sanh
for(I=0;i<n;i++){
if(a[I]<a[imin]) {imin=I;}
}
cout<<" so phuc nho nhat cua mang la: ";
a[min].output();
system("pause");
return 0;
}
Lời giải:
#include<iostream>
#include<math.h>
using namespace std;
class sophuc{
private:
int thuc;
int ao;
public:
sophuc(){
thuc=ao=0;
}
void input();
void output();
float modull(){
return sqrt(pow(thuc,2)+pow(ao,2));
}
int operator < (sophuc);
};
void sophuc::input(){
cout<<" nhap phan thuc = " ;
cin>>thuc;
cout<<" nhap phan ao = ";
cin>>ao;
}
void sophuc::output(){
if(ao<0) cout<<thuc<<"-"<<ao<<"i"<<endl;
else cout<<thuc<<"+"<<ao<<"I"<<endl;
}
int sophuc::operator < (sophuc x){
return (modull()<x.modull());
}
int main(){
int I,n,imin=0;
sophuc *a=new sophuc [n];
cout<<"nhap so phan tu cua mang n = ";
cin>>n;
// nhap mang so phuc
for(I=0;i<n;i++){
cout<<" nhap so phuc thu "<<I+1<<endl;
a[i].input();
}
// ham so sanh
for(I=0;i<n;i++){
if(a[I]<a[imin]) {imin=I;}
}
cout<<" so phuc nho nhat cua mang la: ";
a[min].output();
system("pause");
return 0;
}
Nhận xét
Đăng nhận xét