-
June 18th, 2009, 09:49 AM
#1
Trouble with some simple IF Statements
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;
if(a = 0) {
cout << "Too bad";
}
if(a = 1) {
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "The area is ";
cout << length * width ;
}
return 0;
}
-
June 18th, 2009, 10:08 AM
#2
Re: Trouble with some simple IF Statements
Hi,
"if(a = 0)" should be "if(a==0)", etc.
Alan
-
June 18th, 2009, 11:23 AM
#3
Re: Trouble with some simple IF Statements
Just a thought:
Code:
/* 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.
-
June 18th, 2009, 05:08 PM
#4
Re: Trouble with some simple IF Statements
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....
...Don't be afraid, only believe.
-
June 18th, 2009, 05:16 PM
#5
Re: Trouble with some simple IF Statements
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|