Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The following noncompliant code calculates various dimensions of a sphere, given its radius.

Code Block
bgColor#ffcccc

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
bgColor#ffcccc

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
bgColor#ccccff

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;}

...