patterncppModerate
Calculating the area of a circle
Viewed 0 times
circlecalculatingthearea
Problem
This is one of tasks, which I had to do for the recruitment process at some company. Unfortunately they didn't like it so I've decided to share it here for discussion.
CircleArea.h
CircleArea.cpp
Why could the solution have been disliked by the recruiters?
CircleArea.h
#ifndef CIRCLEAREA_H_
#define CIRCLEAREA_H_
//PI Number, with max precision for double (8 bytes)
const double PI = 3.141592653589793115997963468544185161590576171875;
double circleArea(double radius);
#endifCircleArea.cpp
#include "CircleArea.h"
#include
double circleArea(double radius)
{
if(radius < 0)
{
throw std::invalid_argument("Radius cannot be less than zero");
}
return PI * radius * radius;
}Why could the solution have been disliked by the recruiters?
Solution
I assume one of the complaints was with the constant. There are various ways to calculate pi, using an exact calculation rather than using some number of digits.
Here's one example (in C++14):
(For C++11, use a non-
The
Here's one example (in C++14):
constexpr auto pi()
{
return std::acos(-1);
}(For C++11, use a non-
auto type, such as double or float.)The
constexpr keyword will allow this to be calculated at compile time. You could still assign the return value to a constant or call the function inline where needed. If you don't have C++11, then you can use const in place of constexpr, and just assign it to a constant.Code Snippets
constexpr auto pi()
{
return std::acos(-1);
}Context
StackExchange Code Review Q#94936, answer score: 11
Revisions (0)
No revisions yet.