Возвращение случайного значения вместо ожидаемых значений! C ++ - PullRequest
0 голосов
/ 03 июля 2019

Всякий раз, когда я спрашиваю площадь или периметр, он возвращает некоторые абсурдные значения.Я пытался исправить это в течение 2 дней, но это то же самое!Код и класс приведены ниже вместе с выводом!

Я ожидаю, что выход будет равен 100, но он показывает

252134578 <<<< этот </p>

основной код :

#include <iostream>
#include "rect_class.hpp"

using namespace std;

int main()
{
    rectangle rect;
    int width= 10, height = 10, choice, newwidth, newheight;
    bool loop = false;
    while(loop == false){
        cout << endl << endl;
        cout << " *** Menu *** " << endl;
        cout << "(1) Draw Rectangle" << endl;
        cout << "(2) Area" << endl;
        cout << "(3) Perimeter" << endl;
        cout << "(4) Resize" << endl;
        cout << "(5) Quit" << endl;
        cout << "Enter your choice :";
        cin >> choice;
        cout << endl;

        switch(choice){
            case 2 :cout << rect.getArea();
                break;
            case 3 : cout << rect.getPerimeter();
                break;
            case 4 : cout << "enter your height : ";
                   cin >> newheight;
                   cout << "enter your width : ";
                   cin >> newwidth;
                   rect.setHeight(newheight);
                   rect.setWidth(newwidth);
              break;
            case 5 : loop = true;
                cout << "exiting...";
                break;
            default: cout << "bro type the menu nums !!";
                break;
        }
    };

rect_class.hpp

class rectangle {
public :
    int getHeight() const {return itsHeight;}  //accessors
    int getWidth() const {return itsWidth;}
    void setHeight(int height){itsHeight = height;}
    void setWidth(int width){itsWidth = width;}
    int getArea();
    int getPerimeter();
private :
    int itsHeight;
    int itsWidth;
};

int rectangle::getArea(){
    return itsWidth*itsHeight;
};

int rectangle::getPerimeter(){
    return 2*(itsWidth*itsHeight);
};

Я нахожусь в первые годы своего путешествия по программированию, извините за любые глупые ошибки!: -)

1 Ответ

1 голос
/ 03 июля 2019

Ваши rectangle ученики не инициализированы.Вы устанавливаете значения для переменных int width= 10, height = 10, но не передаете их конструктору класса rectangle.

Измените этот код:

rectangle rect;
int width= 10, height = 10, choice, newwidth, newheight;

На это:

int choice=0, newwidth=0, newheight=0; //always initialize variables!
rectangle rect(10, 10); //create rectangle with 10, 10

Теперь вам нужно добавить конструкторы в класс rectangle:

class rectangle {
public:
rectangle() = delete; //we don't need it anymore
rectangle(int width = 0, int height = 0) : itsHeight(height), itsWidth(width ) { }
//... rest of your code

Этот конструктор позволяет создавать rectangle с заданными параметрами или просто создавать с параметрами по умолчанию (0,0).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...