2.7.1. circle.cpp

Time: 00:03:19 | Download: Large, Large (CC), Small | Streaming Streaming (CC),
\[a = \pi r^2 \]
The area of a circle. The program reads the circle's radius, r, from the console, squares it, and multiplies it by the irrational number π. C++ has no exponentiation operator, so the program must use the pow function or multiply the radius by itself. The program also uses the symbolic constant M_PI for the mathematical value π. Please review the <cmath> header file for details about M_PI.

Test Cases

There is only one easy, practical test case: r = 1, which yields a = 3.141592 (we can also use r = 0, which produces 0, but that provides little assurance that the program is operating correctly). There is no shortcut here: we must choose a set of test inputs arbitrarily and use a calculator to calculate the results manually.

  r a
Case 1 2 12.5664
Case 2 2.75 23.7583

Microsoft Visual Studio

Although I try to restrict the programming examples to generic, ANSI-compliant features, it's not always possible to complete a program without them. Microsoft Visual Studio requires the unusual and non-standard #define _USE_MATH_DEFINES directive to use the symbolic constants (just the constants, not the functions) contained in the math library, and the directive must appear before any of the #include statements. Other ANSI compilers do not require the directive, but it doesn't cause problems if we include it in a program compiled with non-Microsoft compilers.

Programs

#define _USE_MATH_DEFINES	// Microsoft only
#include <iostream>
#include <cmath>		// for M_PI
using namespace std;

int main()
{
	double	r;
	cout << "Radius: ";
	cin >> r;

	double	a = M_PI * r * r;
	cout << "Area = " << a << endl;

	return 0;
}
#define _USE_MATH_DEFINES	// Microsoft only
#include <iostream>
#include <cmath>		// for pow and M_PI
using namespace std;

int main()
{
	double	r;
	cout << "Radius: ";
	cin >> r;

	double	a = M_PI * pow(r, 2);
	cout << "Area = " << a << endl;

	return 0;
}
Area of a circle. The first version uses self-multiplication, r * r, which works here because r is raised to a small integer power. The second version uses the pow function to square r. Please see Exponentiation And The pow Function.