Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Function Overloading Practice | Some Advanced Topics
C++ Functions

book
Function Overloading Practice

Завдання

Swipe to start coding

Create program for a shape calculator that uses function overloading to calculate the area of different shapes (rectangle, circle, and triangle). These functions will have the same name but will be able to calculate area for different types of figures.

Your task is to create overloaded calculateArea() functions. All arguments must have double type:

  • The first function must have two positional arguments, length and width (the order of arguments must be the same!).
  • The second function must have one argument named radius.
  • The third function must have three arguments, a, b and c. These arguments represent the length of all sides of the triangle.

Рішення

cpp

solution

#include <iostream>
#include <cmath>

const double PI = 3.14159;

// Function to calculate area of a rectangle
double calculateArea(double length, double width) {
return length * width;
}

// Overloaded function to calculate area of a circle
double calculateArea(double radius) {
return PI * pow(radius, 2);
}

// Overloaded function to calculate area of a triangle
double calculateArea(double a, double b, double c) {
double s = (a + b + c) / 2; // Calculate semi-perimeter
double area = sqrt(s * (s - a) * (s - b) * (s - c)); // Heron's formula
return area;
}

int main() {
// Calculate and display area for different shapes
std::cout << "Circle - Area: " << calculateArea(3) << std::endl;
std::cout << "Rectangle - Area: " << calculateArea(4, 6) << std::endl;
std::cout << "Triangle - Area: " << calculateArea(5, 4, 6) << std::endl;
}
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 4. Розділ 2
#include <iostream>
#include <cmath>

const double PI = 3.14159;

// Function to calculate area of a rectangle
double calculateArea(___, ___) {
return length * width;
}

// Overloaded function to calculate area of a circle
double calculateArea(___) {
return PI * pow(radius, 2);
}

// Overloaded function to calculate area of a triangle
double calculateArea(___, ___, ___) {
double s = (a + b + c) / 2; // Calculate semi-perimeter
double area = sqrt(s * (s - a) * (s - b) * (s - c)); // Heron's formula
return area;
}

int main() {
// Calculate and display area for different shapes
std::cout << "Circle - Area: " << calculateArea(3) << std::endl;
std::cout << "Rectangle - Area: " << calculateArea(4, 6) << std::endl;
std::cout << "Triangle - Area: " << calculateArea(5, 4, 6) << std::endl;
}

Запитати АІ

expand
ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

some-alt