【问题标题】:The code stops running after the entering the values输入值后代码停止运行
【发布时间】:2020-05-10 03:51:48
【问题描述】:
#include<iostream>
#include<cmath>
using namespace std;

class Complex
{
    private:
        double real;
        double imag;
        double modulus;

    public:
        Complex(){
            cout<<"Default constructor is called"<<endl;
        }
        Complex (double realIn, double imagIn){
            this->real = realIn;
            this->imag = imagIn;
        }
        Complex (const Complex &a ){
            real = a.real;
            imag = a.imag;
            modulus = a.modulus;
        }
        double getModulus(){
            return modulus = sqrt(real * real + imag * imag);
        }
        void display(){
            cout<<real<<" + "<<imag<<" i"<<endl;
        }
        bool operator > (const Complex &c1){
            return modulus > c1.modulus? true : false;
        }
        Complex& operator = (const Complex &c1){
            real = c1.real;
            imag = c1.imag;
            modulus = c1.modulus;
        }               
};

int main(){
    int num, i,j;
    double real, imag;
    cout<<" Input number of complex numbers: ";
    cin>>num;
    Complex* c[num];

    for (i = 0; i < num; i++){
        cout<<"Imput the real part of the complex number no."<<i+1<<endl;
        cin>>real;
        cout<<"Input the imagine part of the complex number no."<<i+1<<endl;
        cin>>imag;
        c[i] = new Complex(real, imag);
        c[i]->display();
    }
    for (i = 0; i < num; i++){
        for (j = i +1; j < num; i++){
            if (c[j]->getModulus() > c[i]->getModulus() ? true:false){
                if (true){
                   Complex* temp = c[j];
                   c[j] = c[i];
                   c[i] = temp;
            } 
            }
        }
    }
    system("CLS");
    cout<<"The decreasing order of the complex numbers is: "<<endl;
    for (i = 0; i < num; i++){
        cout<<i+1<<" : ";
        c[i]->display();
    }

    return 0;
}

我刚开始学习 OOP,尤其是重载函数。我被要求阅读复数列表并按降序打印(使用它们的模数进行比较)。但是,在我输入所有复数后它会停止。没有错误,所以我不知道我哪里弄错了。请帮我。非常感谢!

【问题讨论】:

    标签: c++ oop operator-overloading


    【解决方案1】:

    首先,添加

    #include<cstdlib>
    

    源码开头使用system("CLS");

    其次,改变

    for (j = i +1; j < num; i++){
    

    for (j = i +1; j < num; j++){
    

    (增加j 而不是i)以避免使i 太大。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2015-01-31
      • 2021-05-02
      • 1970-01-01
      • 2019-04-13
      • 2021-05-17
      相关资源
      最近更新 更多