Question: I get the following error when attempting to compile this C++ code: 'else' without previous 'if' with the second count to the global
I get the following error when attempting to compile this C++ code:
" 'else' without previous 'if' "
with the second count to the global variable uncommented "//g_comparisons++;" I need the program to count the comparisons while leaving the else if statements there. I NEED the IF ELSE statements included. (not changed to IF)
Please help, I do not know why I am getting an error upon attempting to add to the global variable in the second instance. Thank you.
CODE :
// //
//Include necessary header directives #include
//Declare global variable to be used for counting int g_comparisons;
int main() { //Declare variable for user input int wavelength; //Prompt user for wavelength input cout << "Please enter a wavelength between 400 and 700 : " << endl; //Store user input in wavelength variable cin >> wavelength; //Set global variable to 0 for counting g_comparisons = 0; //Count comparison in global variable g_comparisons++; //Compare user input to 400 if (wavelength < 400) { //Inform user wavelength is too small cout << "Your wavelength input was too small, exiting program." << endl; cout << "The number of conditional comparisons completed: " << g_comparisons << endl; }
//Count comparison in global variable //g_comparisons++; //Compare user input to 445 else if (wavelength < 445) { //Print wavelength output color cout << "Your corresponding wavelength is Violet" << endl; cout << "The number of conditional comparisons completed: " << g_comparisons << endl; } //Compare user input to 475 else if (wavelength < 475) { //Print wavelength output color cout << "Your corresponding wavelength is Indigo" << endl; } //Compare user input to 510 else if (wavelength < 510) { //Print wavelength output color cout << "Your corresponding wavelength is Blue" << endl; } //Compare user input to 570 else if (wavelength < 570) { //Print wavelength output color cout << "Your corresponding wavelength is Green" << endl; } //Compare user input to 590 else if (wavelength < 590) { //Print wavelength output color cout << "Your corresponding wavelength is Yellow" << endl; } //Compare user input to 650 else if (wavelength < 650) { //Print wavelength output color cout << "Your corresponding wavelength is Orange" << endl; } //Compare user input to 700 else if (wavelength < 700) { //Print wavelength output color cout << "Your corresponding wavelength is Red" << endl; } //Assume user input is over 700 and print error else { //Inform user that the input was too large cout << "Your wavelength input was too large, exiting program." << endl; }
//Print termination statement to user cout << "Thank you for using the Wavelength Program. Good-bye!" << endl; return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
