Illegal else without matching if [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm getting this error message that says illegal else without matching if. I think something is wrong with my else statement, but I don't see where. Do I have an unneeded bracket? It's on line 78 column 2. Thank you
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string service_code, //hold the service code
account_number; //hold the account number
double final_amount = 0, // hold the final amount
final_damount, //hold the amount for the day minutes
minutes = 0, //hold the amount for minutes
day_minutes = 0, // hold the amount for fay minutes
night_minutes = 0, //hold the amount for night minutes
final_namount = 0; //hold the amount for night minutes
cout << "Please enter your account number: ";
cin >> account_number; //Entering the account number
cout << "Please enter your service code (r or R for regular service and p or P for premium service): ";
cin >> service_code; //Enteringthe service code
cout << "Please enter the amount of minutes used: ";
cin >> minutes; //Entering the minutes you used
if(service_code == "r" || "R")
{
if(minutes <= 50)
final_amount = 10;
cout << "Your final amount is $: " << final_amount << endl; //Displaying final amount when your minutes are less than or equal to 50
}
{
if(minutes > 50)
final_amount = (minutes - 50) * 0.20 + 10;
cout << "Your final amount is: $ " << final_amount << endl; //Displaying final amount when your minutes are greater than 50
}
{
else if(service_code == "p" || "P")
cout << "Please enter the amount of minutes used during the day: " << day_minutes << endl; //Entering minutes used during the day
cout << "Please enter the amount of minutes used during the night: " << night_minutes << endl; //Entering minutes used during the night
}
{
if(day_minutes <=75)
final_damount = 0;
final_amount = final_damount + final_namount + 20; //Calculating final amount for minutes used during the day
}
{
if(day_minutes > 75)
final_damount = day_minutes * 0.10;
final_amount = final_damount + final_namount + 20; //Calcuating final amount for minutes used during the day
}
{
if(night_minutes <= 100)
final_namount = 0;
final_amount = final_damount + final_namount + 20; //Calcuating final amount for minutes used during the night
}
{
if(night_minutes > 100)
final_namount = night_minutes * 0.05;
final_amount = final_damount + final_namount + 20; //Calcuating final amount for minutes used during the night
cout << "Your final amount is: $ " << final_amount << endl; //Displaying final amount
}
{
else
cout << "Error, this program does not accept negative numbers.\n"; //Displaying error message
cout << "Account number: " << account_number << endl; //Displaying account number
cout << "Service code: " << service_code << endl; //Displaying service code
cout << "Service code: " << minutes << endl; //Displaying minutes
}
return 0;
}

Most of your if statements are missing their opening curly-braces. This means that the completely wrong code is actually being executed by your program because only the first statement after each if statement will be executed if the conditional expression is true and the rest of the code will always be executed.
...this is the same issue as Apple's infamous goto error bug: http://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/
C is not Python, indentation is not respected by the compiler and it does not mean code belongs to a certain keyword or block.
I strongly suggest reading up on C's syntax, and it's (generally) a good idea to always use curly-braces with all statement blocks (if, for, do, while, etc) to help avoid nasties like these. Internally, my team at Microsoft, runs a program called StyleCop which won't let us check-in code to our central repository if it contains any brace-less statements.

Related

C++ Mortgage payment calculator formula

I've been working on a mortgage calculator for my C++ class. However, I am stuck.
I got the following formula off of Nerdwallet and tried to implement it in my program:
M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1]
M=mortgage payment
P=Principal
i=interest
n=number of payments
Here's the code that I am currently using.
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main(int argc, char** argv)
{
int years, homePrice, creditScore, totalPayments;
float rate, mortgageTotal, monthlyPayment;
cout << "What is the price of the home that you are looking to mortgage?\n";
cin >> homePrice; //Assigns the variable homePrice to a value
cout << "What is your credit score?\n";
cin >> creditScore; //Assigns the creditScore variable a value
cout << "Would you prefer a 15 year or 30 year mortgage? Please type 15 or 30.\n";
cin >> years;
if ( years = 15 ) //If input is 15 year it will go down this logical path
{
if (creditScore >=760) //If their credit rating is equal to or more than 760, their rate will be .043 also nested if.
{
rate = .043;
cout << "Your interest rate is 4.3%\n";
}
else if (creditScore >= 700) //If their credit rating is equal to or more than 700, their rate will be .0455
{
rate = .0455;
cout << "Your interest rate is 4.55%\n";
}
else if (creditScore >= 660) //If their credit rating is equal to or more than 660, their rate will be .048
{
rate = .048;
cout << "Your interest rate is 4.8%\n";
}
else if (creditScore >= 620) //If their credit rating is equal to or more than 620, their rate will be .058
{
rate = .058;
cout << "Your interest rate is 5.8%\n";
}
else if (creditScore >= 580) //If their credit rating is equal to or more than 580, their rate will be .0655
{
rate = .0655;
cout << "Your interest rate is 6.55%\n";
}
else if (creditScore >= 500) //If their credit rating is equal to or more than 500, their rate will be .083
{
rate = .083;
cout << "Your interest rate is 8.3%\n";
}
}
else if ( years=30 )
{
if (creditScore >= 760)
{
rate=.043;
cout <<"Your interest rate is 4.3%\n";
}
else if (creditScore >= 700)
{
rate=.0455;
cout << "Your interest rate is 4.55%\n";
}
else if (creditScore >= 660)
{
rate=.048;
cout << "Your interest rate is 4.8%\n";
}
else if (creditScore >= 620)
{
rate=.058;
cout << "Your interest rate is 5.8%\n";
}
else if (creditScore >= 580)
{
rate=.0655;
cout << "Your interest rate is 6.55%\n";
}
else if (creditScore >= 500)
{
rate=.083;
cout << "Your interest rate is 8.3%\n";
}
}
totalPayments = years * 12;
monthlyPayment = homePrice * [[rate * (1 + rate)pow(totalPayments)] / [(1 + rate)pow(totalPayments) - 1]];
mortgageTotal = monthlyPayment * totalPayments;
cout << "Your mortgage will cost approximately " << mortgageTotal << " and your monthly payment will be " << monthlyPayment << endl;
return 0;
}
However, when I go to compile it, I get the following errors:
Errors
I just don't understand the errors and why they are there.
If someone could help me, I'd greatly appreciate it.
Thank you.
While your math formula uses both []s and ()s for grouping expressions, only ()s can be used in such a way in C++.
pow is a function call, not an in-place operator like you seem to be using it. It needs to look like pow(1 + rate, totalPayments).
Your ifs also are doing assignments (=) instead of comparisons (==). As it is, your code will only follow the first if because it is setting years to 15.
Your mortgage formula seems wrong. Try this
monthlyPayment = homePrice * ((rate * pow(1 + rate, totalPayments)) /
(pow(1.00 + rate, totalPayments) - 1));

I keep getting the same number for number of minutes premium service was used and amount due

I keep getting a fixed number for Number of minutes premium service was used and for amount due. I have tried putting parentheses, and it still gives me a fixed number. Also I have tried to change the addition signs for multiplication and still I get a fixed number. If there is anything else wrong with my code please point it out I'd appreciate it.
#include <iostream>
using namespace std;
int main()
{
int Account_Number;
char Service_Code;
float Regular_Service_Standard_Fee = 10.00;
float Regular_Service_Additional_Fee = 0.20;
float Premium_Service_Stanard_Fee = 25.00;
float Premium_Service_Day_Fee = 0.10;
float Premium_Service_Night_Fee = 0.05;
int Regular_Service_Minutes;
int Premium_Service_Day_Minutes;
int Premium_Service_Night_Minutes;
int Total_Premium_Service_Minutes;
float Amount_Due = 0;
cout << "Enter account number. \n";
cin >> Account_Number;
cout << "Enter service code. \n";
cin >> Service_Code;
cout << "Enter number of minutes the service was used. \n";
cin >> Minutes;
if (Service_Code == 'R' || Service_Code == 'r') {
cout << "Regular service selected. \n";
cout << "Enter number of minutes used. \n";
cin >> Regular_Service_Minutes;
}
else if (Service_Code == 'P' || Service_Code == 'p') {
cout << "Premium service selected. \n";
cout << "Enter the number of minutes used during the day. \n";
cin >> Premium_Service_Day_Minutes;
cout << "Enter the number of minutes used during the day. \n";
cin > Premium_Service_Night_Minutes;
Total_Premium_Service_Minutes = Premium_Service_Day_Minutes + Premium_Service_Night_Minutes;
}
else
cout << "Error! Select R or P! \n";
if (Regular_Service_Minutes > 50)
Amount_Due = Regular_Service_Minutes - 50 * Regular_Service_Additional_Fee + Regular_Service_Standard_Fee;
else
Amount_Due = Regular_Service_Standard_Fee;
if (Premium_Service_Day_Minutes > 75)
Amount_Due = (Premium_Service_Day_Minutes - 75) + Premium_Service_Day_Fee;
else if (Premium_Service_Night_Minutes > 100)
Amount_Due = (Premium_Service_Night_Minutes - 100) + Premium_Service_Night_Fee;
else
Amount_Due = Amount_Due + Premium_Service_Stanard_Fee;
cout << "Account # : " << Account_Number << endl;
cout << "Type of service : " << Service_Code << endl;
cout << "Number of minutes regular telephone service was used : "
<< Regular_Service_Minutes << endl;
cout << "Number of minutes premium telephone service was used : "
<< Total_Premium_Service_Minutes << endl;
cout << "Amount Due : " << Amount_Due << endl;
return 0;
}
Hello and welcome to Stack Overflow (SO).
A few pointers:
Try to make your code readable. Refactor! Refactoring will not only show you where your code lacks the attention, but it will expose logical errors too.
Always initialise your variables when they live inside a scope. C++ will initialise your variables only when it comes for free.
#local scope:
void foo()
{
int num; //num is undefined - i.e. garbage value
}
# global scope
int num; //num is 0.
floats should ideally be followed by a .f to avoid converting from a double. ex: float b = 10.0f;
Create a simplified version of your program and run it on rextester.com to make sure that it works, before posting on SO.
I've tried to quickly simplify your code below and it seems to work for me. I'm not sure about the logic of your program though. You may want to revisit a few sections.
The code can be found here. (click on show input and enter the values for the cin before you run the code on rextester)

C++ while loop not running [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
my while loop wont run on the conditions I set it.
The purpose of the program is to determine the amount of years it will take a deposited amount to mature using the deposit amount, interest rate and target amount.
The program just stops after the target amount has been entered, unless I change the while statement from <= to >= in which case it runs the loop but returns the number of years set at round 100's or 1000 etc...
#include <iostream>
#include <iomanip>
#include <string>
#include <math.h>
using namespace std;
int main()
{
//declare the variables
double rate,
balance = 0;
int deposit,
target,
years = 0;
cout << "****Lets make you some money!****" << endl << endl;
//input from the user
cout << "What is your deposit amount?: " << endl;
cin >> deposit;
cout << "What is your interest rate?: " << endl;
cin >> rate;
cout << "What is you target savings amount?: " << endl;
cin >> target;
rate = rate / 100;
while (balance <= target); //when i change this to balance >= target the 'while' runs but just returns years divisible by 100
{
// calculation
balance += deposit * pow((1 + rate), years);
//balance = balance*(1 + rate) + deposit; // alternate calculation
//years++;
//users savings target
cout << "You will reach your target savings amount in: " << balance << " years." << endl << endl << " That's not that long now is it?" << endl;
}
return 0;
}
Thanks in advance!
The problem is an unfortunate suffix:
while (balance <= target);
// ^
That is equivalently:
while (balance <= target) {
;
}
{
// calculation, which always runs exactly once
// regardless of what balance/target are
}
Just drop the semicolon.

How can i make my functions stops executing at a certain line?

I wrote this this for a simple vendding machine, and this code is to calculate the back change under 1 dollar.
The only problem I am facing is: I want my function to stop excuting the rest of the function if the second if statement in the void function is true.
So, How can I do it?
#include <iostream>
#include <string>
using namespace std;
void changecalculator (int purchaseAmount, int& Qav, int& Dav, int& Nav,int& totalPurchases, int& purchases)
{
int changeAvailable;
//set the variables for the change back function.
int QBack ,DBack ,NBack ;
//calculating the change that the machine should give back.
int chaneBack = 100 - purchaseAmount ;
//test if the purchase amount is a multiple of 5.
if (purchaseAmount %5 == 0)
{
//printing the purchase amount to the screen for the customer.
cout << "You entered a purchase amount of " << purchaseAmount << " cents." <<endl;
cout <<endl;
//calculating the denominations of the change.
QBack = std::min(chaneBack / 25, Qav) ; //Calculating quarters back.
chaneBack -= QBack * 25 ; // subtract the back quarters from the back change.
DBack = std::min(chaneBack/10, Dav); //Caculating the back dimes.
chaneBack -= DBack* 10; //Subtracting the back dimes from the back change.
NBack = std::min(chaneBack/ 5, Nav); //Calculating the back nickels.
chaneBack = QBack*25 + DBack*10 + NBack*5 + chaneBack; //Caculating the change back by adding the denominations.
changeAvailable = Qav * 25 + Dav * 10 + Nav * 5 ;
if (changeAvailable < chaneBack )
{
cout << "No Enough change for the purchase." <<endl;
cout << "Thanks for using my program" <<endl;
}
else
{
}
//Caculating the number of the coins that should be given to the customer as a change.
int coinsNum = QBack + DBack + NBack;
//printing information amount the back change given to the customer.
cout <<"Your change of " <<chaneBack <<" cents is given as " <<QBack <<" Q, " <<DBack <<" D,and " <<NBack <<" N." <<endl;
cout << "The value of your " <<coinsNum <<" coins adds up to " <<chaneBack <<" cents." <<endl;
cout << "Thank you for using my program." <<endl;
//Subtract the given denominations from the available denominations.
Qav -= QBack;
Dav -= DBack;
Nav -= NBack;
//Print visual information for the number of the remaining denominations.
//This part is only to show that the program can keep track of coins.
cout << "Quarters available: " <<Qav <<endl;
cout << "Dimes available: " <<Dav <<endl;
cout << "Nickels available: " <<Nav <<endl;
cout << "total purchases: " <<totalPurchases <<endl;
cout << "purchases: " <<purchases <<endl ;
/* set back the variable the original value so we can keep going
with function that would run after this step if the customer annswered yes. */
chaneBack -= chaneBack;
}
else
{
//print out an error if the purchase amount is not a multiple of 5.
cout << "Unable to process an invalid purchase amout of " <<purchaseAmount <<" cents." <<endl;
cout << "Thank you for using my program." <<endl;
}
}
int main()
{
//set the variables
int Qav=0 ; //Quarters available
int Dav=0 ; //Dimes available
int Nav=0 ; //Nickels available
int purchaseAmount ; //The purchase amount
int totalPurchases = 0; //The total of puchases the cusomer did.
int purchases = 0; //The number of purchases the cutomer did.
string answer; //The answer of the customer (y/n)
//The header of the program
cout << "Simple Vending Program for Adam Ashouri (Regular Version)" <<endl;
cout <<endl;
cout <<endl;
//Get the puchase amount from the customer.
cout << "Enter a purchase amount [5 - 100] -->";
cin >> purchaseAmount;
//Calculating the total of the purchases by adding them together.
totalPurchases += purchaseAmount;
//Calculating the number of purchases.
purchases += 1;
changecalculator (purchaseAmount, Qav, Dav, Nav, totalPurchases, purchases);
//asking the customer if they want to do another ourchase.
cout << "Process again (y/n)?";
cin >> answer;
//this loop helps rerun the function everytime the customer wants to.
while(answer == "y")
{
//Enter the new purchase amount
cout << "Enter a purchase amount [5 - 100] -->";
cin >> purchaseAmount;
//adding the second purchase amount to the last amount.
totalPurchases += purchaseAmount;
//adding this purchase to last number of purchases.
purchases += 1 ;
//run the function to caculate the change for the new purchase amount
changecalculator (purchaseAmount, Qav, Dav, Nav, totalPurchases, purchases);
//asks if the customer wants to do another ourchase again.
cout << "Process again (y/n)?";
cin >> answer;
}
}
You will want to call return.
if (changeAvailable < chaneBack )
{
cout << "No Enough change for the purchase." <<endl;
cout << "Thanks for using my program" <<endl;
return;
}
Add a return statement to your code. return:
Terminates the execution of a function and returns control to the calling function (or to the operating system if you transfer control from the main function). Execution resumes in the calling function at the point immediately following the call.
Source: MSDN
Applied to your code:
...
if (changeAvailable < chaneBack )
{
cout << "No Enough change for the purchase." <<endl;
cout << "Thanks for using my program" <<endl;
return;
}
...
You can do so in one of two ways:
Instead of having nothing in your else block, put everything else (that you don't want to run in the event that your if block is executed) in this block.
Put a return; at the end of your if block. This will cause your function to quit instead of executing any further code.

C++ Output error

I have a problem with my program and I would appreciate help.
It's supposed to allow you to enter an account number, a service code, and the number of minutes the service was used. The program then calculates the bill and it varies depending on your service. When I execute the program, it doesn't allow you to enter anything.
Regular service:$10.00 plus first 50 minutes free. Charges for over 50 minutes are $0.20 per minute.
Premium service:
$25.00 plus:
a)
For calls made from 6:00 am to 6:00 pm, the first 75 minutes are free; charges for over
75 minutes are $0.10 per minute.
b)For calls made from 6:00 pm to 6:00 am, the first 100 minutes are free; charges for over 100 minutes are $0.05 per minute.
Here is the program that I've typed.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int minutes = 0,
day_minutes = 0, //minutes used during the day
night_minutes = 0; //minutes used during the night
string service_code,
account_number;
double final_amount,
final_damount, //final amount for day minutes
final_namount = 0; //final amount for night minutes
cout << "Please enter your account number: ";
cin >> account_number;
cout << "Please enter your service code (r or R for regular service and p or P for premium service): ";
cin >> service_code;
if (service_code == "r")
{
cout << "Please enter the amount of minutes used: " << minutes << endl;
}
if (minutes <= 50)
{
final_amount = 10;
cout << "Your final amount is $: " << final_amount << endl;
}
if (minutes > 50)
{
final_amount = (minutes * 0.20) + 10;
cout << "Your final amount is $: " << final_amount << endl;
}
else if (service_code == "p")
{
cout << "Please enter the amount of minutes used during the day: " << day_minutes << endl;
cout << "Please enter the amount of minutes used during the night: " << night_minutes << endl;
}
if (day_minutes <=75)
{
final_damount = 0;
final_amount = final_damount + final_namount + 20;
}
if (day_minutes > 75)
{
final_damount = day_minutes * 0.10;
final_amount = final_damount + final_namount + 20;
}
if (night_minutes <= 100)
{
final_namount = 0;
final_amount = final_damount + final_namount + 20;
}
if (night_minutes > 100)
{
final_namount = night_minutes * 0.05;
final_amount = final_damount + final_namount + 20;
cout << "Your final amount is: $ " << final_amount << endl;
}
else
cout << "Error, this program does not accept negative numbers.\n";
return 0;
}
Does anyone the problem to my program? Thank you.
In your code you never specify to ask for user input (read from any input streams or files), hence it doesn't ask for any input.
You will probably want to somewhere do something such as cin or cin.readline or any of several other various methods to read the user's input from stdin.
To avoid duplicating other questions I'm not putting further details here.