Hello,
This is my first post at the forum and I'm looking forward to a good experience.
I'm having some trouble with something that I'm pretty sure is really simple. I'm just starting to learn C++ and I'm using Visual C++ 2008 Express Edition.
My program is supposed to first ask the user if he would like to find out the area of a triangle if the user puts in say 0 and Ive predefined that 0 is a no which would make the compter display Too Bad
If the person types 1 and hits enter he would be asked for the length and width then the area will be displayed.
The thing is no matter what I do it always goes for yes.
This is the code:
/* A program designed to calculate the area of a rectangle */
#include <iostream>
using namespace std;
int main ()
{
int length, width, a;
cout << "Would you like to calculate the area of a rectangle?\n";
cout << "Type 1 for yes and 0 for no";
cin >> a;
/* A program designed to calculate the area of a rectangle */
#include <iostream>
using namespace std;
int main ()
{
int length, width;
char a:
cout << "Would you like to calculate the area of a rectangle?\n";
cout << "Type Y for yes and N for no";
cin >> a;
if((a == 'Y') || (a == 'y'))
{
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "The area is ";
cout << length * width ;
}
else
{
cout << "Too bad";
}
return 0;
}
In the code you wrote previously, the code will fail miserably if the user inputs anything apart from 0 or 1. The code I have given you executes the functionality you want if the user inputs 'Y' or 'y' else does print Too Bad...
Regards,
Bhushan.
Hi there,
In C++ " = = " test for equality on some data types, and " = " is just the assignment operator, so by writting if (a = 0) you are only re-assigning the value of a, which will result to a true statement and will always execute, same thing with the second if statement.
your program should work by doing these changes, however if you want a more error proof code you can always try bushan's code, and when you learn to manipulate strings you can even design one that will not fail at all....
Bookmarks