When inputting any letter (F, R, or G) every if statement prints in the compiler.
Im not sure as to why this is the case but some answers would be nice!
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int tmp;
float precip;
char frg;
cout << "Fall 2018 Automated \"Bruin\" Golf Course Sprinkler System" << endl;
cout << endl << "What is the temperature in degrees(F)? ";
cin >> tmp;
cout << "How much precipitation today (in inches)? ";
cin >> precip;
cout << "The Golf Course grass divisions are F-Fairways, R-Rough, G-Greens.";
cout << endl << "Which do you choose (FRG)? ";
cin >> frg;
if (frg == 'R' && precip < 0.835 && tmp > 38)
{
cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
cout << "The Rough on the Golf Course will be watered.";
} else
{
cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
cout << "The Rough on the Golf Course will NOT be watered.";
}
if (frg == 'F' && precip < 0.525 && tmp > 38)
{
cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
cout << "The Fairways on the Golf Course will be watered.";
} else
{
cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
cout << "The Fairways on the Golf Course will NOT be watered.";
}
if (frg == 'G' && precip < 0.325 && tmp > 38)
{
cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
cout << "The Greens on the Golf Course will be watered.";
} else
{
cout << endl << "Given the temperature is " << tmp << " degrees and " << precip << " inches of precipitation today." << endl;
cout << "The Greens on the Golf Course will NOT be watered.";
}
return 0;
}
Even when i input R when asked for the frg variable, all the if statements are printed in the compiler. Please help!
Thank you.
All the if statements are printed
That is not what is happening. Only one of the if statements are printed, but the other 2 else statements (from the other 2 ifs) are also printed because the if will fail.
I commented your code a bit.
if (frg == 'R' && precip < 0.835 && tmp > 38) {
// ... your code
} else {
// Execution will reach this block when frg != R || precip > 0.835 || tmp < 38
// So if you typed F or G, this else will be executed
}
if (frg == 'F' && precip < 0.525 && tmp > 38) {
// ... your code
} else {
// Execution will reach this block when frg != F || precip > 0.525 || tmp > 38
// So if you typed R or G, this else will be executed
}
if (frg == 'G' && precip < 0.325 && tmp > 38) {
// ... your code
} else {
// Execution will reach this block when frg != G || precip > 0.325 || tmp < 38
// So if you typed R or F, this else will be executed
}
As to what you should do to 'fix' this, i can't really suggest anything because I don't know what the desired behavior is.
Hope this clears things up,
Cheers.
your logic seems correct, it should only go into one of those if statements based on your input character. are you sure it's not hitting one IF and then the other 2 ELSES??
you can add
return;
to the end of your the logic inside of your { } brackets, that would ensure that only one logic { } bracket would execute...
or you would need a nested if/else statement to make sure only 1 { } bracket is executed.
as you have it now you are running 1 if, and then 2 elses based on the character
Related
I have a basic menu program that gives the user different programs to choose from and run, when I run the simpleCalculator option and iput values and the operation of arithmetic the output is always the wrong answer but when I first programmed the calculator program without the menu and it being in its own function it would run just fine and give the the right answers, what exactly is going wrong here?
Ignore the third option in the menu since i haven't added code for the prime number checker program
double first_arg;
double second_arg;
string arithmeticOperation;
int numBottles = 99;
double simpleCalculator()
{
cout << "Enter first value: ";
cin >> first_arg;
cout << "Enter choice of arithmetic operation:\n* = multiplication\n/ = division\n+ = addition\n- = subtraction\n\n";
cin >> arithmeticOperation;
cout << "\nEnter second value: ";
cin >> second_arg;
if(arithmeticOperation == "*")
{
cout << "\nYour answer is " << first_arg * second_arg;
}
else if(arithmeticOperation == "/")
{
cout << "\nYour answer is " << first_arg / second_arg;
}
else if(arithmeticOperation == "+")
{
cout << "\nYour answer is " << first_arg + second_arg;
}
else if(arithmeticOperation == "-")
{
cout << "\nYour answer is " << first_arg - second_arg;
}
else
{
cout << "\nPlease enter a valid choice of an arithmetic operation\n";
}
}
string bottlesProgram()
{
while(true)
{
if (numBottles > 2)
{
cout << numBottles << " bottles of beer on the wall\n" << numBottles << " bottles of beer!\n" << "Take one down\nPass it around\n" << numBottles - 1 << " bottles of beer on the wall.";
cout << "\n\n";
}
else if(numBottles == 2)
{
cout << numBottles << " bottles of beer on the wall\n" << numBottles << " bottles of beer!\n" << "Take one down\nPass it around\n" << numBottles - 1 << " bottle of beer on the wall.";
cout << "\n\n";
}
else if(numBottles == 1)
{
cout << numBottles << " bottle of beer on the wall\n" << numBottles << " bottle of beer!\n" << "Take one down\nPass it around\n" << numBottles - 1 << " bottles of beer on the wall.";
cout << "\n\n";
}
else if(numBottles == 0)
{
cout << "No more bottles of beer on the wall,\nNo more bottles of beer.\nGo to the store and buy some more,\n" << "99 bottles of beer on the wall...";
cout << "\n\n";
}
else
{
break;
}
numBottles--;
}
}
int main()
{
int menuInput;
cout << " ***Programs Menu***\n" << "------------------------------------------\n" << "1. Run a simple Calculator\n" << "2. Run 99 bottles of beer on the wall song\n" << "3. Run prime number checker program\n" << "------------------------------------------\n";
cin >> menuInput;
if(menuInput == 1)
{
cout << simpleCalculator();
}
else if (menuInput == 2)
{
cout << bottlesProgram();
}
}
You seem to be confused about returning values from a function, and printing values in a function. These are not the same thing.
If you print the values in the function then the function should be void (i.e. nothing is returned) and the printing happens inside the function (obviously)
void simpleCalculator()
{
...
cout << "\nYour answer is " << first_arg * second_arg;
...
}
simpleCalculator(); // no cout
On the other hand if you return a value from the function then the function is not void and the printing happens outside the function
double simpleCalculator()
{
...
return first_arg * second_arg; // return not cout
...
}
cout << "\nYour answer is " << simpleCalculator();
Your code is doing half one version and half the other.
I have a question regarding if & else statements in a while loop.
I wanted to establish a few things in my program:
wanted user to only input 4 letter characters without the use of numbers and symbols.
converting each those letters into ints(Ascii val.)
To make it easier to understand if confused,
Program 1st asks for 4 letter word.
User places input. If input contains at least:
a non-letter character, then Program asks User for new Input.
If input only contain letters Program checks input for # of letters.
If input doesn't have ___ :
4 letters, Program asks User for new Input.
Otherwise Program proceeds with determining Int value of each letter
Okay so heres my Program so far: ** not sure if this correct for
#include <iostream>
using namespace std;
int main() {
string input;
int input0 = input[0];
int input1 = input[1];
int input2 = input[2];
int input3 = input[3];
cout << "\nEnter a 4-letter word (Keep it clean!).\n";
while(cin>>input){
cout << endl << input << " has " << input.length() << " letters." << endl;
if (int(input[0]) > 64 || int(input[0]) < 91 || int(input[0]) > 96 || int(input[0]) < 123 ||
int(input[1]) > 64 || int(input[1]) < 91 || int(input[1]) > 96 || int(input[1]) < 123 ||
int(input[2]) > 64 || int(input[2]) < 91 || int(input[2]) > 96 || int(input[2]) < 123 ||
int(input[3]) > 64 || int(input[3]) < 91 || int(input[3]) > 96 || int(input[3]) < 123) {
if (input.length()!=5 && input.length()>3)
cout << "\n the int value of the " << input[0] << " is " << int(input[0]) << endl;
cout << "\n the int value of the " << input[1] << " is " << int(input[1]) << endl;
cout << "\n the int value of the " << input[2] << " is " << int(input[2]) << endl;
cout << "\n the int value of the " << input[3] << " is " << int(input[3]) << endl;
else cout << input << "is not a 4-letter word.\nPlease try again." << endl;
}
else cout << input << " contains number(s) and or symbol(s).\nPlease try again." << endl;
}
}
I got 2 errors:
error: expected '}' before 'else'
error: 'else' without a previous 'if'
This fairly gnarly bunch of statements is to blame:
if (input.length()!=5 && input.length()>3)
cout << "\n the int value of the " << input[0] << " is " << int(input[0]) << endl;
// Not part of if-statement:
cout << "\n the int value of the " << input[1] << " is " << int(input[1]) << endl;
cout << "\n the int value of the " << input[2] << " is " << int(input[2]) << endl;
cout << "\n the int value of the " << input[3] << " is " << int(input[3]) << endl;
else cout << input << "is not a 4-letter word.\nPlease try again." << endl;
You need to enclose all those cout statements (up until the else) in braces {, }.
I'd just like to make a point about the character tests you're doing. It looks like you're checking whether the characters are letters, but are using the least-readable, least-portable approach. Use std::isalpha instead. In fact, you can accomplish the whole thing with this:
if( std::all_of( input.begin(), input.begin() + 4, [](char c){ return (bool)isalpha(c); } ) )
{
//...
}
You should do the tests after ensuring the input is the correct length, or you will have undefined behaviour. So let's do that:
while( cin>>input )
{
cout << endl << input << " has " << input.length() << " letters." << endl;
if( input.length() != 4 )
{
cout << input << "is not a 4-letter word.\nPlease try again." << endl;
}
else if( any_of( input.begin(), input.end(), [](char c){ return !isalpha(c); } ) )
{
cout << input << " contains number(s) and or symbol(s).\nPlease try again." << endl;
}
else
{
// I assume you want to exit the loop here.
break;
}
}
Notice I flipped the all_of statement around to the inverse ("any character is not a letter"), for better readability because the lambda no longer needs a cast for automatic type-deduction:
if( any_of( input.begin(), input.end(), [](char c){ return !isalpha(c); } ) ) ...
So I was just making this little calculator program for a game my brother plays just because I was bored. I took a c++ course last semester in college (now taking a java course which I find a bit more confusing) and I just found it fun to make these little programs. Well like usual I'm getting carried away and must be a perfectionist and this is really bothering me.
Now in this game, and like in real life, numbers are seperated by commas to obviously make it easier to read. Because of this, that's mostly how numbers are going to be inputted into the calculator by my brother. Now I could just tell him to not put in any commas when typing in the number and put it in the prompt that there should not be any commas but even then you can't be sure. Even so, it would be best if the code just doesn't mess up every time something that's not a number is put in.
What I've got so far is pretty good. if you put in just letters it will prompt the user again and if you put letters in AFTER the numbers only (not inbetween, that messes it up i found) then it will ignore those letters and work properly. If you put in commas though, it always returns the same thing (0 and 5) although that could be what I'm putting in. I have no idea if the comma is acting as a cut off point or what. Here's the code for getting the integers:
#include <iostream>
using namespace std;
int main() {
int numberofbones, amountofxp, comparableDrag, comparableBaby, comparableDragNoAltar, comparableBigNoAltar, comparableBabyNoAltar;
double comparableBig;
char Gildedaltar, BoneSelection, replay;
bool bFail;
do{
cout << "How many bones do you have?: ";
cin >> numberofbones;
bFail = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (bFail == true);
do{
cout << "How much XP do you need?: ";
cin >> amountofxp;
bFail = cin.fail();
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
} while (bFail == true);
cout << "Are you using a Gilded Altar? (Y/N) ";
prompt:
cin >> Gildedaltar;
comparableDrag = amountofxp / 252;
comparableBig = amountofxp / 52.5;
comparableBaby = amountofxp / 105;
comparableDragNoAltar = amountofxp / 72;
comparableBigNoAltar = amountofxp / 15;
comparableBabyNoAltar = amountofxp / 30;
if (Gildedaltar == 'y' || Gildedaltar == 'Y') {
system("cls");
cout << "What bones will you be using: " << endl;
cout << "a) Dragon Bones " << endl;
cout << "b) Big Bones " << endl;
cout << "c) BabyDragon Bones " << endl;
cin >> BoneSelection;
if (BoneSelection == 'a' || BoneSelection == 'A') {
cout << endl << "With Dragon Bones you need " << comparableDrag << " Bones" << endl;
if (comparableDrag < numberofbones) {
cout << "You have enough bones with " << numberofbones - comparableDrag << " left over, get to sacrafising!" << endl;
}
else {
cout << "You will need " << comparableDrag - numberofbones << " more bones" << endl;
}
}
if (BoneSelection == 'b' || BoneSelection == 'B') {
cout << endl << "With Big Bones you need a total of " << comparableBig << " Bones" << endl;
if (comparableBig < numberofbones) {
cout << "You have enough bones with " << numberofbones - comparableBig << " Left over, get to sacrafising!" << endl;
}
else {
cout << "You will need " << comparableBig - numberofbones << " more bones" << endl;
}
}
if (BoneSelection == 'c' || BoneSelection == 'C') {
cout << endl << "With BabyDragon Bones you will need " << comparableBaby << " Bones" << endl;
if (comparableBaby < numberofbones) {
cout << "You have enough bones with " << numberofbones - comparableBaby << " left over, get to sacrafising!" << endl;
}
else {
cout << "You will need " << comparableBaby - numberofbones << " more bones" << endl;
}
}
}
else if (Gildedaltar == 'n' || Gildedaltar == 'N') {
system("cls");
cout << "What bones will you be using: " << endl;
cout << "a) Dragon Bones " << endl;
cout << "b) Big Bones " << endl;
cout << "c) BabyDragon Bones " << endl;
cin >> BoneSelection;
if (BoneSelection == 'a' || BoneSelection == 'A') {
cout << endl << "With Dragon Bones, you will need " << comparableDragNoAltar << " Bones " << endl;
if (comparableDragNoAltar < numberofbones) {
cout << "You have enough bones with " << numberofbones - comparableDragNoAltar << " left over, get to sacrafising!" << endl;
}
else {
cout << "You will neeed " << comparableDragNoAltar - numberofbones << " More bones" << endl;
}
}
if (BoneSelection == 'b' || BoneSelection == 'B') {
cout << endl << "With Big Bones, you will need " << comparableBigNoAltar << " Bones" << endl;
if (comparableBigNoAltar < numberofbones) {
cout << "You have enough bones with " << numberofbones - comparableBigNoAltar << " Left over, get to sacrafising!" << endl;
}
else {
cout << "You will need " << comparableBigNoAltar - numberofbones << " More bones" << endl;
}
}
if (BoneSelection == 'c' || BoneSelection == 'c') {
cout << endl << "With BabyDragon Bones, you will need " << comparableBabyNoAltar << " Bones" << endl;
if (comparableBabyNoAltar < numberofbones) {
cout << "You have enough bones with " << numberofbones - comparableBabyNoAltar << " Left over, get to sacrafising!" << endl;
}
else {
cout << "You will need " << comparableBigNoAltar - numberofbones << " More Bones" << endl;
}
}
}
else {
goto prompt;
}
}
You can ignore most of the code, I know it probably looks really sloppy and there's probably much betters ways of handling most of the things in here. I just decided to make this out of boredom and figured it could be a good lesson to learn from for me. if you know of a way to help me I would be more than happy to hear the solution, if there's a way to get the program to ignore the commas completly that would be even better but alas I don't believe there's a way to do that.
P.S. please don't get too technical with me, I've only taken one course on this stuff :) Thanks in advance for the help.
You just need to remove the commas from the input string before trying to get an int from it. Better would be to remove any non-digit chars from the input, which you can do with isdigit(). Then call atoi() on it.
string& remove_nondigit(string& s) {
s.erase(remove_if(s.begin(), s.end(), [](const char& c) {
return !isdigit(c);
}), s.end());
return s;
}
yourF() {
string sBones;
cin >> sBones;
cout >> remove_nondigit(sBones);
// you'll want to use atoi() on sBones
}
This question already has answers here:
conditional statement in while loop
(2 answers)
std::cin of char causing infinite loop
(3 answers)
Closed 9 years ago.
So most of my program works fine. It is a program designed to estimate sine and cosine values using Taylor series. The program is designed to quit once the user inputs 0, and then "Y" or "y" upon being asked if they are sure. The char variable exit is initialized to "n", and then is changed if the user inputs y. But the loop doesn't quit then.
#include <iostream>
#include <cmath>
using namespace std;
double calculateFACT(int n); // function that calculates the factorial
double calculateSIN(float, float); // function that approximates the sine
double calculateCOS(float, float); // function that approximates the cosine
int main()
{
int choice; // menu choice
double angle = 0; // angle user inputs, initialied to zero
double calc; // the calculated sine or cosine value
int order; // order approimation value
char exit = 'n'; // exits for yes
do {
cout << "MAIN MENU" << endl;
cout << "1. To enter the data." << endl;
cout << "2. To calculate the sin(x)" << endl;
cout << "3. To approximate the sin(x)" << endl;
cout << "4. To calculate the cos(x)" << endl;
cout << "5. To approximate the cos(x)" << endl;
cout << "6. To re-enter data." << endl;
cout << "Press 0 to quit." << endl;
cout << "Please make a choice: ";
cin >> choice;
cout << endl;
if (choice != 0 &&
choice != 1 &&
choice != 2 &&
choice != 3 &&
choice != 4 &&
choice != 5 &&
choice != 6)
{
cout << "Wrong Choice. Only options 1-6 are available." << endl << endl;
}
if (choice == 1)
{
if (angle == 0)
{
cout << "Please give a value for the angle: ";
cin >> angle;
cout << endl;
}
else cout << "Please use option 6 to enter a new angle." << endl << endl;
}
if (choice == 2)
{
if (angle == 0)
{
cout << "You have to enter a value first!" << endl << endl;
}
else
{
calc = sin(angle);
cout << "The sine of x is " << calc << endl << endl << endl;
}
}
if (choice == 3)
{
if (angle == 0)
{
cout << "You have to enter a value first!" << endl << endl;
}
else
{
cout << "Please give a value for the approximation order n: ";
cin >> order;
cout << "The approximation of sin(" << angle << ") is: " << calculateSIN(angle, order) << endl << endl;
}
}
if (choice == 4)
{
if (angle == 0)
{
cout << "You have to enter a value first!" << endl << endl;
}
else
{
calc = cos(angle);
cout << "The cosine of x is " << calc << endl << endl << endl;
}
}
if (choice == 5)
{
if (angle == 0)
{
cout << "You have to enter a value first!" << endl << endl; // cosine function not giving the right value
}
else
{
cout << "Please give a value for the approximation order n: ";
cin >> order;
cout << "The approximation of cos(" << angle << ") is: " << calculateCOS(angle, order) << endl << endl;
}
}
if (choice == 6)
{
if (angle == 0)
{
cout << "If this is the first time you run this program please choose option 1." << endl << endl;
}
else
{
cout << "Please give new angle: ";
cin >> angle;
cout << endl << endl;
}
}
if (choice == 0)
{
cout << exit;
cout << endl << endl << "Are you sure you want to quit? (Y/N): "; // Y/N option doesnt work
cin >> exit;
}
cout << exit;
} while (exit != 'Y' || exit != 'y');
if (exit == 'Y' || exit == 'y')
{
cout << endl << "Now quitting.." << endl;
system("pause");
return 0;
}
}
double calculateFACT(int n)
{
double nfact = 1;
for (int i = 2; i <= n; i++)
nfact *= i;
return nfact;
}
double calculateSIN(float angle, float order)
{
double sine = angle;
for (int i = 1; i < order; i++)
{
sine += pow(-1.0, i) * (pow(angle, 2 * i + 1)) / calculateFACT(2 * i + 1);
}
return sine;
}
double calculateCOS(float angle, float order)
{
double cosine = 0;
for (int i = 0; i < order; i++)
{
cosine += pow(-1.0, i) * (pow(angle, 2 * i)) / calculateFACT(2 * i);
}
return cosine;
}
I answered a similar question named Why is my c++ code not working properly?. And the answer is exactly the same. You need to do exit != 'Y' && exit != 'y' otherwise it will always evaluate to true.
remyabel answered the question. Your code says "if the user didn't type 'Y' or 'y'", keep running. Since you're only looking for one character, it will keep running forever, since the character cannot be both 'Y' and 'y' at the same time.
Hence, while (exit != 'Y' && exit != 'y') essentially says "if the user didn't type an exit condition, I'm going to keep executing."
I need to use -1 to terminate but still display the summary.
Every time that I've tried and have gotten it to terminate the program, it doesn't go ahead and display the summary.
There are up to 10 trials, if you don't have enough information for 10 and you want to stop at 8, you type -1 and it goes to the summary and then terminates the program
while(i<10)
{
do
{
cout << "Enter result """ << i+1 << """ (or -1 if no more results): ";
cin >> score[i];
if(score[i] >=0 && score[i] <=49)
{
cout << "Grade " << "U" << " will be assigned to this result\n";
bool test=true;
i++;
}
else if(score[i] >=50&& score[i] <=59)
{
cout << "Grade " << "P" << " will be assigned to this result\n";
bool test=true;
i++;
}
else if(score[i] >=60 && score[i] <=69)
{
cout << "Grade " << "C" << " will be assigned to this result\n";
bool test=true;
i++;
}
else if(score[i] >=70 && score[i] <=89)
{
cout << "Grade " << "B" << " will be assigned to this result\n";
bool test=true;
i++;
}
else if(score[i] >=90 && score[i] <=100)
{
cout << "Grade " << "A" << " will be assigned to this result\n";
bool test=true;
i++;
}
else
{
test=false;
cout << "Invalid Input!\n";
}
}
while(test);
}
cout << "\nSummary of the results:\n";
for(int a=0;a< 10;a++)
{
std::cout << std::fixed << std::setprecision(2) << "Result " << a+1 << " " << score[a] << " Grade " << determine_grade(score[a]) << "\n";
}
cout << "\nThe average of the results = " << calc_average(score) << "\n";
cout << "The lowest of the results = " << find_lowest(score) << "\n";
cout << "The highest of the results = " << find_highest(score) << "\n";
system("Pause");
You don't want two loops, only one. You need to combine your two conditions into one i<10 && test.
Also you have declared your test variable in the wrong places. You should declare it once at the beginning of your loop.
bool test = true;
while(i<10 && test)
{
cout << "Enter result """ << i+1 << """ (or -1 if no more results): ";
if(score[i] >=0 && score[i] <=49)
{
cout << "Grade " << "U" << " will be assigned to this result\n";
i++;
}
...
else
{
test=false;
cout << "Invalid Input!\n";
}
}
Try to use break; when -1 is inputted inside the while loop. Also, you can use 1 loop, instead of two as john mentioned above.
Another thing to look for is your last for loop, it goes from 0 to 9, but in case someone used -1 and only inputted 3 grades, there might be odd values for the solutions.