...
The following noncompliant code calculates various dimensions of a sphere, given its radius.
Code Block | ||
---|---|---|
| ||
double area(double radius){
return 12.56*radius*radius;}
double volume(double radius){
return 4.19*radius*radius*radius;}
double greatCircleCircumference(double radius){
return 6.28*radius;}
|
...
The following noncompliant code attempts to avoid the above issues by explicitly calculating the required constants
Code Block | ||
---|---|---|
| ||
double area(double radius){
return 4.0*3.14*radius*radius;}
double volume(double radius){
return 4.0/3.0*3.14*radius*radius*radius;}
double greatCircleCircumference(double radius){
return 2*3.14*radius;}
|
...
In this compliant solution, a constant PI is first declared and set equal to 3.14, and is thereafter referenced in the code whenever the value pi is needed.
Code Block | ||
---|---|---|
| ||
final int PI = 3.14;
double area(double radius){
return 4.0*PI*radius*radius;}
double volume(double radius){
return 4.0/3.0*PI*radius*radius*radius;}
double greatCircleCircumference(double radius){
return 2*PI*radius;}
|
...