You are here:

C++/C++ if and else problem


#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>

const double PI = 3.14159;

using namespace std;

int main()

char shape;
char c;
char t;
char r;
// input by the user to
// choose T(riangle) , C(ircle), or R(ectangle)

double area ;

double length, width; // for the rectangle
double radius; // for the circle
double base, height; // for the triangle

cout << "This program will calculate the area of a "
<< "\ncircle, a rectangle or a triangle.\n"
<< " \nto calculate a circle area, input C (or c) "
<< " \nto calculate a rectangle area, input R (or r)"
<< " \nto calculate a triangle area, input T ( or t)"
<< " \n\nInput C, T, or R: ";
cin >> shape;

cout << "\nInput the radius of the circle: ";
cin >> radius;

cout << "\nYou have entered " << radius << " as the radius." <<endl;

cout << fixed << showpoint << setprecision(2);

area = PI * pow(radius,2);

cout << "\nThe area of the circle is " << area;

else if(shape=='T'||t)
cout << "Input the base and height of the triangle with a space in between: ";
cin >> base >> height;

cout << "\nYou have entered " << base << " as the base and " << height << " as the height." << endl;

area = (1.0/2.0) * base * height;

cout << "\nThe area of the triangle is " << area;

else if(shape=='R'||r)
cout << "Input the length and width of the rectangle with a space in between: ";
cin >> length >> width;

cout << "\nYou have entered " << length << " as the length and " << width << " as the width." << endl;

area = length * width;

cout << "\nThe area of the rectangle is " << area;

When I run my program and enter the next character such as "T", it will still show me the results as if I entered "C". How do I corrected it so that if I entered T it would show those results.

Hello Peter.

There is a small misunderstanding in the "if" syntax.
When you say

You are asking if shape=='C' is true or if c is true. The variable c is some char which is not initialized to anything, so it very likely contains a non-zero value. A variable which contains a non-zero value evaluates to true, so that is why the first "if" expression is always true, and why the circle code is always executed.

In this case you want to see if shape is either of the characters 'C' or 'c'. The syntax would be
if (shape == 'C' || shape == 'c')
Do the same correction for all the other if statements.

Also, there is no need for
char c;
char t;
char r;
You should remove those.

Best regards


All Answers

Answers by Expert:

Ask Experts




No longer taking questions.


No longer taking questions.

No longer taking questions.

©2016 All rights reserved.