C++ programming ... stuck on if..else if... conditions - c++

I created this little software which can calculate the surface and the perimeter of the rectangle and the square. However, it is getting very hard for me to run this program. What I mean is that when I try to run it, the software works fine for the "square" part, but it closes immediately when I go to the "rectangle" part. Can anyone help me? Thank you very much!
#include<iostream>
using namespace std;
int main ()
{
double a, b, c, answer, x, y, z;
cout << "Square (1) or rectangle (2) ";
cin >> x ;
if (x==1)
{
cout << "Square side: ";
cin >> a;
cout << " Type (2) if you would like to calculate the Perimeter or (1) if you would like to calculate the surface?";
cin >> y;
if (y == 1)
{
cout<<"The surface of the square is: ";
answer = ( a * a );
cout << answer << endl;
}
else if (y == 2)
{
cout << "The perimeter of the square is: ";
answer = (4*a);
cout << answer << endl;
}
else if (x==2)
{
cout << "The first side of the rectangle is: ";
cin >> c;
cout << "The second side of the rectangle is: ";
cin >> b;
cout << " Type (2) if you would like to calculate the Perimeter or (1) if you would like to calculate the surface? ";
cin >> z;
if (z == 1)
{
cout << "The surface of the rectangle is: ";
answer = (c*b);
cout << answer<<endl;
}
else if (z == 2)
{
cout << "The perimeter of the rectangle is: ";
answer = 2 * (c + b);
cout << answer << endl;
}
}
system("pause");
return 0;
}

You are missing a closing brace before else if (x==2)
It is a good idea to make the indentation match the braces - easier to spot this type of bug
`

You have a curly bracket(}) missplaced. You need to close it before else if (x==2) because otherwise the else if applies to else if (y==2) instead to x == 1. Improve your code style as pointed in IntermediateHacker's comment and you should be able to avoid such errors.

I have spend a lot of time formatting your code. Still there are obvious problems with it. The curly braces just do not match. You don't even have opening brace for the main method. You also do not have curly brace before else if (x==2). If you have paid some more effort formatting your code it would have been easier for you to detect your problem.

Related

How do I keep asking the user a question over and over again until they enter the correct field of value?

I am a rookie coder here and I can't seem to figure out what to add to my code here to get it right. It is supposed to ask the user again if they do not answer the question "Do you want to make another calculation Y or N?" correctly. I want it to repetitively ask the user to enter y or n if they enter something else. I feel like it is obvious I am just missing it. This is for school, to be clear.
I've tried nesting a do while loop and an if statement but only to get run time errors
#include <iostream>
using namespace std;
int main() {
int base, exponent;
long int result = 1;
char choice;
int i;
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
// ***** HERE IS WHERE I NEED HELP, WHAT TO
// DO IF THEY DONT ENTER Y OR N.....
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
}
while (choice == 'y' || choice == 'Y');
cout << "Good bye, then. Have a good day.\n" << endl;
return 0;
}
When I tried adding a nested do while loop, and entered a character answer other than y or n, it would go to a part of the program it should not have.
*this is my first question so I hope I've done this correctly
You can use another do-while loop to wrap the input section.
do
{
cout << "This program raises a number to a specific power." << endl;
cout << "\nEnter a base integer greater than 1: ";
cin >> base;
cout << "\nEnter an exponent integer to raise that number to: ";
cin >> exponent;
for (i = 1; i <= exponent; i++)
{
result = result * base;
}
cout << "\n" << base << " to the power of " << exponent << " = " << result << endl;
result = 1;
do
{
cout << "\nWould you like to make another calculation? Y or N: ";
cin >> choice;
cout << endl;
} while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N');
}
while (choice == 'y' || choice == 'Y');
Learn to think organically here. Let me do a procedural approach.
We begin by bringing your formulations into a more technical form, until it is syntactically and semantically working. Let's start by transforming it into this:
void process_things()
{
...
while(still_require_answer)
{
ask_for_answer();
}
...
}
This is very close to how you formulate it verbally, yes? Now, let's flesh it out.
string ask_for_answer(bool& still_require_answer);
void process_things()
{
...
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
answer = ask_for_answer(still_require_answer);
}
...
}
// hope you understand the concept of a reference here,
// that is what the ampersand (&) does, if not, ask
string ask_for_answer(bool& still_require_answer)
{
string answer = ""; // always initialize
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
return answer;
}
Hope this helps you. In the long run, you might want to go OOP and use classes here. The code here is a little bit verbose, but orderly.
Note that I have put the routine in a new function process_things. Anything that is more than a few lines which you can name you should think about making a function (or a class method). Your main should be quite small. Cutting things down into smaller units helps you keeping thisng orderly and makes the design of each single unit easy (divide-and-conquer) and allows you to quicker locate problems as you can test every function separately (later, this leads to automated unit tests).
One could also take the while and put it into it's own function string ask_until_valid_answer();, and if we do that, dissolve ask_for_answer and put it's content there. What I want to focus on is to have it organically, that is use self-descriptive names which explain the program while reading it, and to cut the program into understandable units. Here would be this other layout:
string ask_until_valid_answer();
void process_things()
{
...
string answer = ask_until_valid_answer();
...
}
string ask_until_valid_answer()
{
string answer = "";
bool still_require_answer = true;
while(still_require_answer)
{
cout << "State answer: ";
cin >> answer;
cout << endl;
if(answer == "Y" or ...)
{
still_require_answer = false;
}
}
return answer;
}

C++ for loop variable increment by another variable

I have been working on a simple grade calculator, I am having trouble with the "labs" option spitting back a bad result, I am looking for a decimal percent, but I keep getting a very very large exponential number.
The specific part I am having trouble with is the calclabavg() function-- the for loop to be exact.
I am not asking for an exact solution, I just want to be pointed in the right direction so that I can solve the problem on my own.
Thanks so much in advance :)
float calclabavg(){//funciton that calculates user lab averages
float x, vary, pointspos, sumpointspos, sumearned;
cout << "How many labs in labs?" << endl;
cin >> x;
float totalpoints = 0;
cout << "Do the points vary per lab? (Press 1 for yes, 0 for no)" << endl;
cin >> vary;
if (vary == 0){
cout << "How many points were possible on each lab?" << endl;
cin >> pointspos;
sumpointspos = x * pointspos;
}
for (int i = 0; i < x; i++){
float temp;
cout << "What was your score on lab " << i + 1 << endl;
cin >> temp;
sumearned += temp;
if (vary == 1){
cout << "How mant points possible on lab " << i + 1 << endl;
float pointsposvary;
cin >> pointsposvary;
sumpointspos += pointsposvary;
}
//pointspos = pointspos + temp;
}
return sumearned / sumpointspos;
}
It seems as if you do not initialize sumearned.
Statement sumearned = 0.0; at the beginning of calclabavg should bring you at least a step further. BTW: initialising also the other variables is good practice and makes code more stable.

C++ - Loop function or program forever? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Made my first C++ program ever. A basic calculator.
Got stuck at this part where I was suppose to make the program repeat.
So at "Point A" you select if you want to count division/addition etc. and it takes you there. When you run it once, it asks if you want to repeat the function (e.g division) or go back to the "Point A" (you just type y[yes] (repeats the division) or n[no](goes to "point A")).
I'm new to C++, haven't got really familiar with loops yet.
Also the code structures make my head spin, so Google didn't help me much.
I've heard about the "goto" function (or whatever you call it) but I was told that i shouldn't be used in this case.
Take a look. The texts, and most of the comments are in Finnish, but I hope you'll get the point from English comments.
#include <iostream>
using namespace std;
float addition(float num1, float num2)
{
return num1 + num2;
}
float substraction(float num1, float num2)
{
return num1 - num2;
}
float multiplication(float num1, float num2)
{
return num1 * num2;
}
float division(float num1, float num2)
{
return num1 / num2;
}
//This function should throw you back to point 'A'
int valinta2{
while (valinta2 == y){
}
}
int main(void)
{
//Point A
float number1;
float number2;
int valinta;
cout << "\n-*-*-*-*-*-*-*-*-*-*\nClaudion Laskin\n-*-*-*-*-*-*-*-*-*-*";
//Select what you want to count
cout << "\n\n\nValitse mita haluat laskea. \n\nVaihtoehdot: " << endl;
cout << "1. Plus-laskut\n 2. Vahennys-laskut\n 3. Kerto-laskut\n 4. Jako-laskut \n\nValinta: ";
cin >> valinta;
if (valinta == 1){
//Addition
cout << "\n\n\n===============\n||Plus laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n+\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << addition(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 2){
//Subtraction
cout << "\n\n\n===================\n||Vahennys laskut||\n=================== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n-\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << substraction(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cout << "Valinta: ";
cin >> valinta2;
}
else {
if (valinta == 3){
//Multiplication
cout << "\n\n\n================\n||Kerto laskut||\n================ \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n*\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << multiplication(number1, number2) << "\n----------\n" << endl;
cin.get();
//if 'y' run the task again, if 'n' goto start
cout << "-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\nKirjoita 'y' jos haluat jatkaa, 'n' jos haluat valikkoon\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n";
cin.get();
}
else {
if (valinta == 4){
//Division
cout << "\n\n\n===============\n||Jako laskut||\n=============== \n\nSyota ensimmainen numero: ";
cin >> number1;
cout << "\n\n/\n\nSyota toinen numero: ";
cin >> number2;
cout << "\nTulos: " << division(number1, number2) << "\n----------\n" << endl;
}
}
}
}
system("pause");
return 0;
}
You need to restructure your code to include the while loop in the main method. There would be ways to "go to" your "Point A", but they are messy and shouldn't be used (goto is the keyword here).
So at "Point A", insert
do {
float number1;
// ...
and then down at where you would like to call valinta2 (notice that you don't even call the function at the moment - I'm guessing it would have to be just before the call to system("pause")), do the check of the condition, like so:
} while (...);
And best revisit the chapter on flow control/loops in the C++ tutorial of your choice, e.g. one of those mentioned here: The Definitive C++ Book Guide and List
Alternative to nyarlathotep's perfectly good answer, one method I like using follows this form:
while(true) {
//do stuff
//then when ready to check for exit condition
if(exitCondition == true) { //the ==true part is redundant
break;
}
//do more stuff
//if you need to go to the beginning of the loop and
//skip any code following a point, do this:
if(skipRestOfLoopCondition) {
continue;
}
//you can always check other exit conditions or check
//the same one at multiple places
if(someOtherExitCondition) {
break;
}
//do even more stuff
}
system("pause");
return 0;
As a caveat, you must provide a way for at least one of the if's that result in break; to actually execute, because while(true) loop condition never gets you out of the loop, you can only get out of the loop with a break;.
I am pretty new to this and I don't know if I am right. I can hardly understand your code. However, when I am programming in c for the arduino and I want my code to loop forever I just put
void loop() {// my code follows from here

Function not working correctly?

I am trying to create an exponent function and it does not seem to work as expected. Sorry if I don't understand some basic things, I'm just learning bits and pieces off the internet.
float x;
float y;
float z;
int h;
int j;
float exponent (float a, float b)
{
float r;
while(b > 1)
{
r = a * a;
b = b - 1;
}
return (r);
}
^Snippet of the function with variables.
cout << "EXPONENT MODE\n\n";
cout << "Please enter a number: ";
cin >> x; system("CLS");
cout << "Please enter another number as the exponent for the first: ";
cin >> y;
z = exponent(x, y);
cout << "Calculating the answer, please wait";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << ".";
Sleep(1000);
cout << "\n\nYour answer is : ";
cout << r;
Sleep(5000);
system("CLS");
cout << "Would you like to calculate another set of numbers? (yes = 1, no = 2) : ";
cin >> h;
system("CLS");
^Part I want to execute on the console.(Just code)
Basically, I want the user to input 2 numbers, the first(x) being the base number, the second(y) being the exponent. The program should input x as a and y as b and run the function. What happened: Input 1: 5, Input 2: 3, Expected: 125, Received: 25. I'm thinking about changing the while to (b > 0). If you guys could help that would be great!.
(Also don't judge me on the system("CLS") in the code)
It's fairly simple, you're printing the wrong variable.
cout << "\n\nYour answer is : ";
cout << r;
r is a local member variable of exponent. In the scope of main, the result of exponent was actually stored in a variable called z
z = exponent(x, y);
The fix is just to change your answer printing code to
cout << "\n\nYour answer is : ";
cout << z;
For your own benefit, you might want to try giving your variables more meaningful names and only declaring them in scopes where they are actually needed. I don't see you using r elsewhere in main, did you make it global in an attempt to try and make the r in exponent accessible there too?
I dont under stand what #kfsone is talking about.
but in the loop r is set as a*a everytime, isn't this why you are getting the square instead of exponent ? I think what you really want to do is this:
r=1
while( ...
r *= a;// note to accumulate result on r
b --;

C++ code, bools, and loops

I am new to C++ programming and haven't done anything in a week, so I was messing around with things I know thus far to see if I have to go over things again.
However, I ran into an issue with bools (haven't really used them before).
Source:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
signed long int x;
unsigned short int y = 12345;
bool POSX;
bool yes;
cin >> x;
if (x >= 0)
{
POSX = true;
}//end of if for bool
else
{
POSX = false;
}
cout << "This is the current value of X: " << x << endl;
if(x < y)
{
cout << "x is less than the integer y \n \n";
}//end of if
else
{
cout << "y is greater than the integer x \n \n";
}//end of else
cout << "The current value of Y is: " << y << endl << endl << endl;
cout << "Is X positive?: " << POSX << endl << endl;
cout << "How much more would X need to be to surpass y? The answer is: " << y - x << endl;
if(x > y)
{
cout << "well, actually, x is greater than y by: " << y - x << " so you would need to add that to get to the value of x" <<endl <<endl;
}//end of if
cout << "Do you like cookies? Enter below. . ." <<endl;
cin >> yes;
if(yes = "yes") // should this be if(yes = 1)?
{
cout << "I do too! But only when they are soft and gooey!";
} //end of if for bool yes
else
{
cout << "Well, join the dark side, and you may be persuaded by the power of cookies and the power of the dark forces!";
}//end of else for bool yes
char f;
cin >> f;
return 0;
} //end of main
The issue I have is when I try to compile, for one, the program exits before I can see the result of the cookie question [so I have to place a break point in the compiler], and second, when I can see the answer, it always comes up with the yes response, and not anything else.
So, if I put no as the input, it still outputs the if for the bool yes being true. I am not sure if I am defining the if clause correctly in the last statement.
Could anyone help?
Ok, two things. Your major problem is this:
if(yes = "yes")
'yes' is definend as a bool type, i.e., it can hold the values "true" or "false". You attempting to compare comparing (actually attempting to assign due to using only one = instead of ==, which is how you check for equality) a boolean to a string "yes". Well, that makes no sense. It should be:
if( yes )
That's it. 'yes' is already a boolean, and the expression in an if statement requires no more.
Secondly, constructs like this are redundant and unnecessary:
if (x >= 0)
{
POSX = true;
}//end of if for bool
else
{
POSX = false;
}
You are checking for a boolean value and then assigning one. Just do it in one line like this:
POSX = (x >=0 );
Also, you typically don't use all caps for local variables.
One more thing; you are entering string data ("no" or "yes") and cin is expecting an int. I suggest that you spend some time learning about what data types are.
The issue I have is when I try to compile, for one, the program exits before I can see the result of the cookie question
That's because you invalidated cin when you put "no" as the value. operator>>(std::istream&, bool&) assumes numeric input. Values not equal to zero will be interpreted as true, and values equal to zero will be interpreted as false.
If you supply input that cannot be parsed as numeric badbit will be set on the stream. Attempting to use the stream while it is in this failed condition will result in garbage being read (or rather, undefined behavior), and no advancement of the get pointer in the stream.
Change yes to a string(#include <string>), and then compare it like this:
if (yes == "yes")
There are a couple of things going wrong here, but I think the one tripping you up is cin >> yes; In C++, false is 0. Therefore, this will likely return true for any non-zero input values. A more reliable approach would be to ask for and evaluate on something else, for instance, character input:
cout << "Do you like cheese? (y/n) ";
char c;
cin >> c;
if ( c == 'y' || c == 'Y' )
do whatever;
Additionally, when testing conditionals, be sure to use "double-equals", condition == true. Better yet, adopt the shorthand where:
(condition) means (condition == true)
(! condition) means (condition == false)
Hope that gives you a start in the right direction.
Here is the edited sources code, I made changes so study it and compare with the original code. *e*
#include <iostream>
#include <string>
#include <iomanip> //headerfile for boolalpha
using namespace std;
int main()
{
string answer;
signed long int x;
unsigned short int y = 12345;
bool POSX;
bool yes;
cout<<"Enter any value: ";
cin >> x;
if (x >= 0)
{
cout << boolalpha; // print bools as true or false
POSX = true;
}//end of if for bool
else
{
cout << boolalpha; // print bools as true or false
POSX = false;
}
cout << "This is the current value of X: " << x << endl;
if(x < y)
{
cout << "x is less than the integer y \n \n";
}//end of if
else
{
cout << "y is greater than the integer x \n \n";
}//end of else
cout << "The current value of Y is: " << y << endl << endl << endl;
cout << "Is X positive?: " << POSX << endl << endl;
cout << "How much more would X need to be to surpass y? The answer is: " << y - x << endl;
if(x > y)
{
cout << "well, actually, x is greater than y by: " << y - x << " so you would need to add that to get to the value of x" <<endl <<endl;
}//end of if
cout << "Do you like cookies? Yes/No. . ." <<endl;
cin >> answer; //this is a string
if(answer =="yes") // it can be a simple if statement
{
cout << "I do too! But only when they are soft and gooey!";
} //end of simple if
else
{
cout << "Well, join the dark side, and you may be persuaded by the power of cookies and the power of the dark forces!";
}//end of else for simple if
return 0;
} //end of main`