01/10/2018, 00:32
Các bác giúp em sửa bài Vector
Các bác giúp em thực hiện phép toán cộng, trừ, nhân, chia bài vector này với ạ.
Chỗ cộng, trừ, nhân, chia bị lỗi
#include <iostream>
#include <math.h>
using namespace std;
class Vector{
private:
int n;
float *a;
public:
void Nhapn(){
cin >> n;
}
void Init(){
cout << "Nhap " << n << " so thuc" << endl;
for(int i=0; i<n; i++){
cout << "a[" << i << "]: ";
cin >> a[i];
}
}
Vector(int n=0){
a = new float[n];
for(int i=0; i<n; i++)
a[i] = 0;
}
Vector(const Vector &v){
a = new float[n];
for(int i=0; i<n; i++)
a[i] = v.a[i];
}
~Vector(){
delete a;
}
void Show(){
for(int i=0; i<n; i++)
cout << a[i] << " ";
cout << endl;
}
int DieuKien(Vector &v2){
if(this->n == v2.n) return 1;
else return 0;
}
Vector Add(Vector &v){
Vector kq;
for(int i=0; i<this->n; i++)
kq.a[i] = a[i] + v.a[i];
return kq;
}
Vector Sub(Vector &v){
Vector kq;
for(int i=0; i<n; i++)
kq.a[i] = a[i] - v.a[i];
return kq;
}
float Mult(const Vector &v){
float S=0;
for(int i=0; i<n; i++)
S += a[i] * v.a[i];
return S;
}
Vector Mult(float k){
Vector kq;
for(int i=0; i<this->n; i++)
kq.a[i] = k * a[i];
return kq;
}
void Sort(){
float temp;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++){
if(a[i] < a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
};
int main(){
Vector v1,v2,v3;
cout << "Nhap du lieu cho vector1" << endl
<< "Nhap n = ";
v1.Nhapn();
v1.Init();
cout << "Nhap du lieu cho vector2" << endl
<< "Nhap n = ";
v2.Nhapn();
v2.Init();
cout << "
-----------------------------
"
<< "Hai vector vua nhap" << endl;
cout << "v1: ";
v1.Show();
cout << "v2: ";
v2.Show();
cout << "
-----------------------------
"
<< "Cong hai vector" << endl;
if(v1.DieuKien(v2) == 1){
v3=v1.Add(v2);
cout << "v1+v2: ";
v3.Show();
}
else cout << "Khong cong duoc" << endl;
cout << "
-----------------------------
"
<< "Tru hai vector" << endl;
if(v1.DieuKien(v2) == 1){
v3=v1.Sub(v2);
cout << "v1-v2: ";
v3.Show();
}
else cout << "Khong tru duoc" << endl;
cout << "
-----------------------------
"
<< "Nhan hai vector" << endl;
cout << "v1*v2 = " << v1.Mult(v2);
cout << "
-----------------------------
";
float k;
cout << "
Nhap so thuc k: ";
cin >> k;
cout << "Nhan vector1 voi so thuc k = " << k << endl;
v3=v1.Mult(k);
v3.Show();
cout << "
-----------------------------
"
<< "Sap xep phan tu vector1 tang dan" << endl;
v1.Sort();
v1.Show();
return 0;
}
Bài liên quan
delete chia động từ số nhiều.
là thêm “s” vào sau á bác?
Hàm
Vector Mult(float k);Add(Vector &v);Sub(Vector &v)
thì kq.n =0; bạn phải cho kích thước kq.n và cáp phát bộ nhớ cho kq.av3=v1.Add(v2);
-> việc gán này sẽ làm 2 Vector cùng giữ một con trỏa
nên bị lỗi. Bạn nên viết lại operator =delete a;
->delete []a;