Please have a look at the following code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double balance=0;
int withdraw = 0;
double const bankCharges = 0.5;
cin >> withdraw >> balance;
if(withdraw%5==0 && balance>(withdraw+bankCharges))
{
cout << fixed << setprecision(2) << ((balance)-(withdraw+bankCharges)) << endl;
}
else if(withdraw%5!=0 || withdraw>balance)
{
cout << fixed <<setprecision(2) << balance << endl;
}
return 0;
}
The above code is created to address the below challenge
http://www.codechef.com/problems/HS08TEST
As you can see, my code is providing the correct answer. But the test engine says "wrong answer" !!!!! Why? Please help!
Never leave the if, else if block without an else condition if there is even a slight possibility to reach there. Add the else condition to your code.
if(withdraw%5==0 && balance>(withdraw+bankCharges))
{
cout << fixed << setprecision(2) << ((balance)-(withdraw+bankCharges)) << endl;
}
else if(withdraw%5!=0 || withdraw>balance)
{
cout << fixed <<setprecision(2) << balance << endl;
}
else
{
//Do something
}
Related
I'm working on a program that I've seen other people do online except I'm trying to use functions to complete it to make it somewhat more challenging for me to help me better understand pointers and vectors. The problem I'm having in xcode is I keep getting this error..
Expected ';' after top level declarator
right here on my code,
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers) //<<< Error
{
cout << fixed << setprecision(2);
...
Where I am trying to use vector numbers in my function. Basically I want the numbers from the function passed back so that I can use them in another function I have not created yet. I've googled this error and it seems like no one can give a straight answer on how to fix this problem. Is anyone familiar with how to correct this? By no means is this code finished I'm just trying to get information regarding vectors as a parameter because from what I'm seeing syntax wise on other sites it looks to be correct. Thanks for your feedback.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
struct menuItemType{
string menuItem;
double menuPrice;
};
void getData(menuItemType (&mlist)[8]);
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
int main() {
vector<int> temp;
menuItemType menuList[8];
getData(menuList);
showMenu(menuList,temp);
/*
cout << menuList[0].menuItem << " " << menuList[0].menuPrice << endl;
cout << menuList[1].menuItem << " " << menuList[1].menuPrice << endl;
*/
return 0;
}
void getData(menuItemType (&mlist)[8]){
string Str;
ifstream infile;
infile.open("cafe135.txt");
if(infile.is_open())
{
for (int i = 0; i < 8; ++i){
infile >> mlist[i].menuItem >> mlist[i].menuPrice;
}
}
else cout << "Unable to open file";
}
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
{
cout << fixed << setprecision(2);
string choice;
cout << "Would you like to view the menu? [Y] or [N]: ";
cin >> choice;
cout << endl;
int x = 3;
int count = 1;
while (choice != "Y" && choice != "N" && choice != "y" && choice != "n")
{
if (count == 4){
return;
}
cout << "Error! Please try again ["
<< x
<< "] selections remaining: ";
cin >> choice;
cout << endl;
x--;
count++;
}
if (choice == "N" || choice == "n"){
return;
}
else
{
cout << "___________ Breakfast Menu ___________" << endl;
for (int i = 0; i < sizeof(menu_List)/sizeof(menu_List[0]); ++i)
{
cout << "Item "
<< (i+1)
<< ": "
<< menu_List[i].menuItem
<< " "
<< menu_List[i].menuPrice
<< endl;
}
cout << endl;
string itemSelection = " ";
//int str_length = 0;
cout << "Select your item numbers separated"
<< " by spaces (e.g. 1 3 5) Select 0 to cancel order: ";
cin.ignore();
getline(cin, itemSelection);
if (itemSelection == "0")
{
return;
}
vector<int> vectorItemSelection;
stringstream text_stream(itemSelection);
string item;
while (getline(text_stream, item, ' '))
{
vectorItemSelection.push_back(stoi(item));
}
int n = vectorItemSelection.size();
int arr[n];
for (int i = 0; i < n; i++)
{
arr[i] = vectorItemSelection[i];
}
}
}
Compare how menu_List is declared in this line
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
and this line
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
The first one is correct.
But I have to agree with the comments above, you are mixing up a lot of different things here. Just use vectors, 99% of the time it's the right thing to do anyway. and it's easier to learn one thing at a time.
Prefer to write your code like this
void getData(vector<menuItemType>&);
void showMenu(vector<menuItemType>&, vector<int> numbers);
int main() {
vector<int> temp;
vector<menuItemType> menuList(8);
...
See? Just use vectors everywhere.
I've started to learn how to code in C++ on my spare time, using different sites and apps that someone who has also learned C++ online provided me with. By now, I know the most basic commands. I've tried an exercise given by a program, and I'm given the information that someone is going on a vacation, and needs to know how much baggage he can bring with him. The limit to how many baggages he can carry is 45, and I have to display a different output if the baggages are below, above or the same as the limit (45 baggages). I have done some coding, and I ended up with this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
cout << "Please type your number here: ";
cin >> bag;
string yn;
int keep = 0;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
++keep;
while(keep > 0)
{
int keep = 0;
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
if(yn == "yes")
{
int bag = 0;
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
}
else
{
return 0;
}
}
}
I have developed it more than needed -as you can see-, out of my own interest in the problem. I have copied and pasted the 3 IF commands as seen above, and I believe that there is an easier way, with less code, do solve this. What I have thought of is if I could go back and execute some line of code again, either from a line and below (e.g. from line 45 and below), or specific lines of code (e.g. from line 45 to line 60).
I would appreciate it if you thought of another way to solve this problem and posted your code below.
Thank you for your reply.
We all started writing our first C++ program at some time, so allow me to give you some additional feedback:
First of all, avoid writing using namespace std;
Secondly, naming - what is bag, limit, keep and yn? Wouldn't it be much easier to read and understand if they were called bagSize, maximumPermittedBagSize, inputFromUser (you don't really need the variable keep, see below)?
Finally, here is a (roughly) refactored version your program, with duplication removed and comments added.
#include <iostream>
int main()
{
const int maximumPermittedBagSize = 45;
// Loops forever, the user exits by typing anything except 'yes' laster
while(true)
{
std::cout << "Please type your number here: " << std::endl;
//Declare (and initialize!) variables just before you need them
int bagSize = 0;
std::cin >> bagSize;
if (bagSize > maximumPermittedBagSize)
{
std::cout << "You passed the limit." << std::endl;
}
else if (bagSize == maximumPermittedBagSize )
{
std::cout << "Just enough." << std::endl;
}
else
{
std::cout << "You got space." << std::endl;
}
std::cout << "Do you want to try another number?" << std::endl;
std::string inputFromUser = "";
std::cin >> inputFromUser;
std::cout << std::endl;
//Leave the loop if the user does not answer yes
if(inputFromUser != "yes")
{
return 0;
}
}
}
You can simply run a while loop and do like this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
string yn = "yes";
while(yn == "yes")
{
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
}
else if (limit == bag)
{
cout << "Just enough." << endl;
}
else if (limit > bag)
{
cout << "You got space." << endl;
}
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
}
}
as recommended I've been working through the book 'Jumping into c++'. I'm currently on problem 7 of chapter 5 and although I have produced the code that appears to do what is asked of me I was hoping someone might be able to take a look and tell me if I've implemented any 'bad' practice (Ideally I don't want to be picking up bad habits already).
Secondly, it also says 'try making a bar graph that shows the results properly scaled to fit on your screen no matter how many results were entered'. Again, the code below produces a horizontal bar graph but I'm not convinced that if I had say 10000 entries (I guess I could verify this by adding an additional for loop) that it would scale according. How would one go about applying this? (such that it always properly scales regardless of how many entries).
I should probably point out at this point that I have not covered topics such as arrays, pointers and classes as of yet in case anyone was curious as to why I didn't just create a class called 'vote' or something.
One final thing... I don't have a 'return 0' in my code, is this a problem? I find it slightly confusing as to what exactly the point of having return 0 is. I know that it's to do with making sure your code is running properly but it seems sort of redundant?
Thanks in advance!
#include <iostream>
using namespace std;
int main()
{
int option;
int option_1 = 0;
int option_2 = 0;
int option_3 = 0;
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
while(option != 0)
{
if(option == 1)
{
option_1++;
}
else if(option ==2)
{
option_2++;
}
else if(option ==3)
{
option_3++;
}
else if(option > 3 || option < 0)
{
cout << "Not a valid entry, please enter again" << endl;
}
else if(option ==0)
{
break;
}
cout << "Which is your favourite sport?" << endl;
cout << "Tennis.. 1" << endl;
cout << "Football.. 2" << endl;
cout << "Cricket.. 3" << endl;
cin >> option;
}
cout << "Option 1 (" << option_1 << "): ";
for(int i = 0; i < option_1; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 2 (" << option_2 << "): ";
for(int i = 0; i < option_2; i++)
{
cout << "*";
}
cout << "" << endl;
cout << "Option 3 (" << option_3 << "): ";
for(int i = 0; i < option_3; i++)
{
cout << "*";
}
}
About the return 0 in main : it's optional in C++.
About your code:
You have a ton of if / else if blocks, you should replace them with a switch. A switch statement is more compact, readable, and may be a little bit faster at runtime. It's not important at this point, but it's pretty good practice to know where to put a switch and where to use regular if.
You have one big function, it's really bad. You should break your code into small, reusable pieces. That's something called DRY (Don't repeat Yourself): if you are copy-pasting code, you're doing something wrong. For example, your sport list appears 2 times in your code, you should move it in a separate function.
You wrote cout << "" << endl;, I think you don't really understand how std::cout work. std::cout is an object representing the standard output of your program. You can use operator<< to pass values to this standard output. std::endl is one of these values you can pass, strings are, too. So you can just write cout << endl;, no need for an empty string.
Please learn how to use arrays, either raw ones or std::array. This is a pretty good example of a program which can be refactored using arrays.
Here is a more readable, cleaner version of your code:
#include <iostream>
int prompt_option()
{
int option;
while (true)
{
std::cout << "Which is your favourite sport?" << std::endl;
std::cout << "Tennis.. 1" << std::endl;
std::cout << "Football.. 2" << std::endl;
std::cout << "Cricket.. 3" << std::endl;
std::cin >> option;
if (option >= 0 && option <= 3)
return option;
else
std::cout << "Not a valid entry, please enter again" << std::endl;
}
}
void display_option(int number, int value)
{
std::cout << "Option " << number << " (" << value << "): ";
while (value--)
std::cout << '*';
std::cout << std::endl;
}
int main()
{
int option;
int values[3] = {0};
while (true)
{
option = prompt_option();
if (option)
values[option - 1]++;
else
break;
}
for (int i = 0; i < 3; i++)
display_option(i + 1, values[i]);
}
You have too much if else, it messy.
check out the code bellow, muc shorter, cleaner and efficent.
I hope it helps.
#include <iostream>
using namespace std;
int main()
{
int choice;
int soccer=0, NFL=0 ,formula1=0;
while(choice != 0){
cout<<"Please choose one of the following for the poll"<<endl;
cout<<"press 1 for soccer, press 2 for NFL, press 3 for formula 1"<<endl;
cout<<"Press 0 to exit"<<endl;
cin>>choice;
if(choice==1){
soccer++;
}
else if(choice==2){
NFL++;
}
else if(choice == 3){
formula1++;
}
else{
cout<<"Invalid entry, try again"<<endl;
}
cout<<"soccer chosen "<<soccer<<" times.";
for(int i=0; i<soccer; i++){
cout<<"*";
}
cout<<endl;
cout<<"NFL chosen "<<NFL<<" times.";
for(int j=0; j<NFL; j++){
cout<<"*";
}
cout<<endl;
cout<<"formula1 chosen "<<formula1<<" times.";
for(int c=0; c<formula1; c++){
cout<<"*";
}
cout<<endl;
}
return 0;
}
I am a newby at this and am working on my fist if/else program. I am having trouble getting the first if statement to recognize my input of "r". I tried playing with just one statement at a time I was able to input all the examples of input the teacher gave us with the desired output for residential and business. However when I run the program altogether I have a problem. I select R for residential, 0 for additional connections, 0 for premium channels and instead of output of $18.50 I get the business fee of $75.00. I am sure it is a simple mistake but I can't figure out what I am doing wrong. Can someone who knows how to work an if/else give me some insight on this!
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const float BASIC_RESIDENTIAL = 18.50;
const float BASIC_BUSINESS = 75.00;
const float CONNECT_RESIDENTIAL = 6.50;
const float CONNECT_BUSINESS = 5.00;
const float PREMIUM_RESIDENTIAL = 7.50;
const float PREMIUM_BUSINESS = 50.00;
char customerType;
int numOfConnections;
int numOfPremiumChannels;
float amountCableBill;
cout << fixed << setprecision(2);
cout << "Residential or Business [R or B]? ";
cin >> customerType;
cout << endl << endl;
cout << "How many Additional Connections? ";
cin >> numOfConnections;
cout << endl << endl;
cout << "Total number of Premium Channels: ";
cin >> numOfPremiumChannels;
cout << endl << endl;
if (customerType == 'R' || customerType == 'r')
{
amountCableBill = BASIC_RESIDENTIAL + CONNECT_RESIDENTIAL * numOfConnections + PREMIUM_RESIDENTIAL * numOfPremiumChannels;
}
//else customerType == 'B' || customerType == 'b'; // unnecessary
{
if (numOfConnections <= 9)
amountCableBill = BASIC_BUSINESS + PREMIUM_BUSINESS * numOfPremiumChannels;
else
amountCableBill = BASIC_BUSINESS + (numOfConnections - 9) * CONNECT_BUSINESS + PREMIUM_BUSINESS *numOfPremiumChannels;
}
cout << "Total amount of Cable Bill: " << amountCableBill << endl << endl;
cout << "Press <ENTER> to end..." << endl;
_getch();
return 0;
}
While the condition else if (customerType == 'B' ...) may be redundant, you still have to put an else before the opening brace of the branch.
It's
if (condition) { code } else { code }
You need else in the condition (unless you want "some other code" to be executed every time)
if (customerType == 'R' || customerType == 'r')
{
//Some Code
}
else //<--Notice else
{
//Some other code.
}
Hi this is my first time using classes so apologies for my poor explanation. Basically I am making a password function for an elevator program. LogIn is the name of my class, which contains the string "john" which is the password. Everything seems to be working fine except the loop for incorrect password attempts.
If the password attempt is correct the first time then the code workds fine, however if a password is entered incorrectly then the line "Incorrect name. Try again" appears for the next two attempts, regardless of whether or not the password has been entered correctly. I was hoping someone could see where I'm going wrong. name is the stored password and nameAttempt is the attempted password inputted bu the user.
#include "stdafx.h"
#include "LogIn.h"
#include <iostream>
#include <iostream>
#include <string>
using namespace std;
bool password() {
string name;
string nameAttempt;
int attempts = 0;
cout << "nameAttempt: " << endl;
cin >> nameAttempt;
LogIn Authenticate(name, nameAttempt);
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
else
while (Authenticate.getName() != Authenticate.getNameAttempt())
{
if (attempts++ ==2)
{
return false;
}
cout<<"Incorrect name. Try again"<< endl;
cout<< "" << endl;
cout << "Enter Name:"<< endl;
cin >>nameAttempt;
}
}
int main()
{
bool password();
bool loggedin = password();
if(loggedin) {
cout << "Password Correct" << endl;
}
if(!loggedin) {
cout << "Incorrect Password" << endl;
cout << "Program will now terminate" << endl;
system("pause");
return 0;
}
cout << "you are now free to enter lift" << endl;
system("pause");
return 0;
}
In the retry loop, you still need to validate the attempted name and break the loop if the name is accepted.
You initialize local function variable
int attempts = 0;
so exit condition in while loop will be trigerred third times the code
if (attempts++ ==2)
is run, so you will print two times:
while (Authenticate.getName() != Authenticate.getNameAttempt())
{
if (attempts++ ==2) // increment attempts
{
return false;
}
It looks as it was done deliberately to exit after second print, so your confusion is hard to understand. Use the debugger, this kind of error is very easy to investigate.
I think the code should be like this:
while (1)
{
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
else
{
if (attempts++ == 2)
{
return false;
}
cout << "Incorrect name. Try again" << endl;
cout << "" << endl;
cout << "Enter Name:" << endl;
cin >> nameAttempt;
Authenticate.setNameAttempt(nameAttempt);
}
}
Try this, sweet and simple:
cout << "nameAttempt: " << endl;
cin >> nameAttempt;
LogIn Authenticate(name, nameAttempt);
attempts = 0;
while (attempts<2)
{
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
cout<<"Incorrect name. Try again"<< endl;
cout<< "" << endl;
cout << "Enter Name:"<< endl;
cin >>nameAttempt;
attempts++;
LogIn Authenticate(name, nameAttempt);
}
return false;