👤

Napisz kod programu, który będzie wyświetlał obwód kwadratu o boku a, a podaje użytkownik. Dopilnuj, by program przyjmował tylko wartości dodatnie.

Odpowiedź :

sprawdzone, działa.

#include <iostream>

#include <clocale>

struct TNegativeLenError{};

class Square

{

private:

int a;

public:

Square() = default;

Square(int x);

int obwod();

};

Square::Square(int x)

{

if (x < 0)

{

 TNegativeLenError exception1;

 throw exception1;

}

else a = x;

}

int Square::obwod()

{

return 4 * a;

}

int main()

{

std::setlocale(LC_ALL, "polish");

int bok;

std::cout << "Wprowadź długość boku:\t";

std::cin >> bok;

Square s;

try

{

 s = Square(bok);

}

catch (TNegativeLenError)

{

 std::cout << "Długość boku nie może być ujemna!\n";

 return 1;

}

std::cout << "Obwód wynosi:\t" << s.obwod();

return 0;

}