Logic Error

Guys I have a logic error in my code and I cant seem to spot it!this program should calculate the circumference of a circle or the perimeter of a rectangle by using overloaded functions. My calculations yield correct answers but yet i dont seem to be getting the if and else clause right. Please advise as the program must only do either the circumference or the perimeter not both. Mine executes both.


#include <iostream>
#include <iomanip>
using namespace std;
// This program calculates the perimeter of a rectangle and the circumference of a circle depending on what calculation the user has selected.
double calcCircumference (double radius)
{
double PI = 3.14285; double circumference;
cout << "Enter radius of the circle: " << endl;
cin >> radius;

circumference = 2 * PI * radius;
cout << "The circumference of the circle is: " << circumference <<endl;

}

double calcrectanglePerimeter (double length , double width)
{
double perimeter;

cout << "Enter the length of the rectangle: " << endl;
cin >> length;
cout << "Enter the width of the rectangle: " << endl;
cin >> width;

perimeter = 2*(length + width);
cout << "The perimeter of the rectangle is: " << perimeter <<endl;

}

int main ()
{
char entered ;

cout << "Press 'c' to calculate circumference of a circle or 'p'to calculate the perimeter of a rectangle: " << endl;
cin >> entered;

if ((entered == 'c' || 'C') && (entered != 'p' || 'P'))
calcCircumference(0);
else

if ((entered == 'p' || 'P') && (entered != 'c' || 'C'));
calcrectanglePerimeter(0,0);


return 0;
}
1
2
3
if (entered =='c' || entered == 'C') calcCircumference(0);
else if (entered == 'p' || entered == 'P') calcRectanglePerimeter(0,0);
else cerr << "Invalid input.\n";


'C' in a context where a value of type bool is expected is always true, since it is non-zero.
So your first condition was eqivalent to:
(entered =='c' || true) && (entered != 'p' || true)
Last edited on
Wow! Thanks Cire it actually works perfectly now! Amazing how one line of code makes all the difference. Thank you.
Topic archived. No new replies allowed.