Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am learning C++. As a homework I've started to try the branching.. but I didn't quite get the hang of it... here's the code I've tried to perform (please bear patience with me if I'm making huge mistakes..)
#include <iostream>
using namespace std;
int main () {
int age;
char * yes;
char * no;
bool Rated = Rated ? yes : no;
int ticketPrice = 5;
int discountPrice = ticketPrice - (ticketPrice * 0.1);
int matineePrice = (ticketPrice * 0.5);
int hour = 8 <= hour <= 24;
cout << "Is the movie R_rated? \n";
cin >> yes or no;
cout << "How old are you?";
cin >> age;
if (age < 0 or age >100) {
cout << "Not a valid age!";
}
else if ((age <= 13) and (Rated = yes)) {
cout << "You must be accompanied by a Janitor";
}
else if (((age > 13) and ((Rated = yes) or (Rated = no)))
or ((age <=13) and (Rated = yes))) {
cout << "What time do you want the ticket for?";
cin >> hour;
if (hour < 8 or hour > 24) {
cout << "Not a valid hour!";
}
else if (hour < 18) {
if (age <= 5) {
cout << "The entrance is free";
}
else if (age >= 55) {
cout << "Matinee Ticket price is "<<
matineePrice;
}
else if (5 < age < 55) {
cout << "Matinee ticket price is " << matineePrice;
}
}
else if (hour >= 18) {
if (age <= 5) {
cout << "The entrance is free";
}
else if (5 < age <= 55) {
cout << "Ticket price is " << ticketPrice;
}
else if (age > 55) {
cout << "You're eligibile for a 10% "
"discount \n";
cout << "Ticket price is " << discountPrice;
}
}
}
}
Output: (to which I answer no, 67, and 20) and I should get the discountedPrice instead of the ticketPrice value...
Is the movie R_rated?
no
How old are you?67
What time do you want the ticket for?20
Ticket price is 5
Any suggestion, link or tutorial help would be really appreciated...
There are a lot of things wrong with your code. I suggest you get a good book on C++ and learn from that. If you're already using a book, chances are that it's not good.
Here are some things, though:
char* is not the right thing to use for strings. You should use the std::string class.
Your entire code surrounding Rated bears little resemblance to C++.
= is the assignment operator. It cannot be used to compare things for equality; that's what == is for.
To start with, get rid of yes and no, which make no sense, and read the input into a string variable:
string Rated;
cin >> Rated;
then to use that, remember to use == not = for comparison:
if (Rated == "yes") {/*whatever*/}
Alternatively, use a boolean variable:
string yes_or_no;
cin >> yes_or_no;
bool Rated = yes_or_no == "yes";
if (Rated) {/*whatever*/}
Also, this:
8 <= hour <= 24
doesn't do what you think it does. You'd need two separate comparisons:
8 <= hour and hour <= 24
although, in this case, you don't want it at all - it doesn't make sense to initialise hour with that. You're reading the value of hour and checking its range later, and don't need to initialise it here.
There are probably more problems, but that should get you started. And I hope I can still go to the cinema when I'm over 100.
The code below is fixed. I've attempted to explain exactly what the code does.
// Declare the input/output streams, including standard streams like std::cin and std::cout.
#include <iostream>
// Declare the std::string class - it's C++, we should not use C strings!
#include <string>
// Instead of using the entire std namespace, we'll only use the things that come up often.
// This saves some typing, but is safe. Otherwise, who knows what name may clash with something
// in the vast std namespace.
using std::cin;
using std::cout;
using std::endl;
int main() {
bool ok; // Whether the most recent answer to a question is valid
bool rated; // Whether the movie is R-rated
int age; // Customer's age
int hour; // Hour of the showing
const int ticketPrice = 5;
const int discountPrice = ticketPrice * (1.0 - 0.9);
const int matineePrice = ticketPrice * 0.5;
// Gather Inputs
do {
std::string answer; // Holds the answer to the yes/no question
cout << "Is the movie R-rated (y/n)? ";
cin >> answer;
if (answer.length() > 0) {
// If the answer is not empty, we can uppercase the first letter.
// This way we don't have to check for lowercase answers.
answer[0] = toupper(answer[0]);
}
// The answer is valid when it's non-empty and when it begins with either Y/y or N/n
ok = answer.length() > 0 and (answer[0] == 'Y' or answer [0] == 'N');
if (not ok) {
cout << "That's not a valid answer." << endl;
} else {
// The answer is valid, so we can set the rated variable.
rated = answer[0] == 'Y';
}
} while (not ok); // Repeat the question while the answer is invalid
do {
cout << "How old are you? ";
cin >> age;
// The answer is valid when it's between 0 and 150, inclusive.
ok = age >= 0 and age <= 150;
if (not ok) {
cout << "That's not a valid age!" << endl;
}
} while (not ok);
do {
cout << "What hour do you want the ticket for? ";
cin >> hour;
// The hour 0 is mapped to 24.
if (hour == 0) hour = 24;
// The answer is valid when it's between 8 and 24, inclusive.
ok = hour >= 8 and hour <= 24;
if (not ok) {
cout << "That's not a valid hour!";
}
} while (not ok);
// Output the Messages
if (rated and age <= 13) {
cout << "You must be accompanied by a Janitor" << endl;
}
if (age <= 5) {
cout << "The entrance is free" << endl;
}
else if (hour < 18) {
cout << "Matinee ticket price is " << matineePrice << endl;
}
else {
if (age <= 55) {
cout << "Ticket price is " << ticketPrice << endl;
}
else {
cout << "You're eligibile for a 10% discount." << endl;
cout << "Ticket price is " << discountPrice << endl;
}
}
}
To start off with:
char * yes;
char * no;
// ...
cin >> yes or no;
makes no coding sense what-so-ever.
In general, "yes" and "no" are not keywords in c++. "true" and "false" are.
Alright, some things:
1)
cin >> yes or no;
should be:
cin >> Rated;
since variable names can't have spaces in them, as you've written it the compiler reads "cin should put something in yes, but I can't figure out what to do with 'or' and 'no'."
2)
else if ((age <= 13) and (Rated = yes))
will never work. I recommend rewriting storing the result in a string (std::string) and then setting rated according to that.
std::string rated_str;
cin >>rated_str;
if(rated_str == "yes") {
rated = true;
} else {
rated = false;
}
and then in the if you use:
if(rated)
or
if(rated == true)
3) You can't reference a variable before it's fully declared:
bool Rated = Rated ? yes : no;
Lines:
bool Rated = Rated ? yes : no;
cin >> yes or no;
and all with
(Rated = yes)
(Rated = no)
have no sense.
First of all, if Rated is bool then you can assign to it only true or false (everything which is not 0 or NULL and what compiler accept would be converted to true).
Best quality code should use enum type for rated.
When you read, you should read to some variable and check its type.
Small fixes for you:
enum EnRated
{
RRated = 0,
NotRRated = 1
};
...
enum EnRated Rated;
string ans; //instead of yes, no
...
cin >> ans;
if(ans == "yes") Rated = RRated;
else Rated = NotRRated; //handle ans != yes or no
...
(Rated == RRated) // instead of (Rated = yes)
(Rated == NotRRated) // instead of (Rated = no)
For discount ticket use:
double discountPrice = 0,9*ticketPrice;
You will input hour and test them, so you can write only:
int hour;
Try this
You are doing a mistake in the following else if statements.
You are not using your else if condition checker properly.
You need not to use or keyword here... actually this is the real problem you are facing here, and you just need to replace your or with and.
For a perfect solution please read the Right approach below
Your code
else if (5 < age <= 55) {
cout << "Ticket price is " << ticketPrice;
}
Right approach
This will give you your discount price
else if (5 < age and age < 55)
{
cout << "Ticket price is " << ticketPrice;
}
Related
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;
}
I have been trying forever to figure out what loop control variable (LCV) to use for my program to work but I have been unsuccessful.
The information given is as follows:
You will be promoting a student for grades and credits for courses taken. From that, you will calculate a GPA.
The course name is prompted for, but nothing is done with it.
We are just using the grades A, B, C, D, and F so you won't have to do so much typing!
You will need to use the "set precision" command as shown in the book. Set it to "fixed" and "2".
You will need to use the "cin.ignore()" function as discussed earlier in the course.
Notes
I used int total to count the number of classes.
Current while statement was my last attempt, and it is not correct.
My code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main () {
cout << std::fixed << std::setprecision(2);
string course, grade, answer;
int credits, total = 0;
float gradePoints = 0, totalCredits = 0;
float gpa = 0.0;
while (grade <= "ABC") {
cout << "Enter a course name: ";
getline(cin, course);
cout << course << endl;
cout << "Enter number of credits: ";
cin >> credits;
cout << credits << endl;
cout << "Enter your grade (A, B, C, D, F): ";
cin >> grade;
cout << grade << endl;
cout << "Continue ('Yes' or 'No')? ";
cin >> answer;
cout << answer << endl;
if (grade == "A") {
gradePoints = gradePoints + 4;
}
else if (grade == "B") {
gradePoints == gradePoints + 3;
}
else if (grade == "C") {
gradePoints = gradePoints + 2;
}
else if (grade == "D") {
gradePoints = gradePoints + 1;
}
else if (grade == "F") {
gradePoints = 0;
}
total = total + 1;
totalCredits = totalCredits + credits;
}
gpa = (total * gradePoints)/ totalCredits;
return 0;
}
Based on the way the rest of the program is written, I'd think that you'd want to check against the user's response to the "Continue?" question. Something like this:
bool answer = true;
while (answer) {
// code
// when ready to exit...
answer = false;
}
That said, it might make more sense to use a do-while loop, where the first block executes before the conditional is checked:
do {
// code
} while (answer != "No");
And while you're at it, you might also want to consider using a different flag than having the user type in "Yes" or "No". Something like y and n is more common and a bit simpler.
"while (grade <= "ABC")"
If the intent is to say only do the loop while grade has a value of A, or B, or C, then:
while(grade == "A" || grade == "B" || grade == "C")
int main() {
power=1;
while (1 == 1){
tapcost=power*3;
cout << "type upgrade/buy/a" << endl;
cin >> way;
if (way == "upgrade"){
cout << "1. A Power " << "(Costs: " << tapcost << ")" << endl;
cin >> upgr;
if (upgr == 1){
if (0<=money-power*3){
power=power+1;
money=money-power*3;
}
else
cout << "You can't afford that!!!" << endl;
}
}
if (way == "a"){
money=money+power;
}
}
return 0;
}
When I type upgrade and then type anything else other than the variable "1", the code will repeat infinitely.
This is a never-ending problem.
See this question: Infinite loop with cin when typing string while a number is expected
I think your code have some mistakes.
int upgr;
cin >> upgr; // you can type any number you want (-2 147 483 648 / 2 147 483 647)
I suggest you to use getline, cin.getline or fgets instead of cin >> when reading a line.
And just use while(1) or while(true)
You have created an infinite loop by never changing the value of your ‘1’ variable. In some way you need to change that value when iterating through your conditions or else you’ll never get out of your loop.
You could also try out something like that.
char i;
while((std::cin >> i) && i != '1') {
....
}
In your code, while (1 == 1) creates an infinite loop. Since I assume you want this code to keep asking players for their input until they decide to stop, you can add an option exit which breaks out of the loop when the player wants to.
#include <iostream>
int main() {
int power = 1;
int money = 1000;
while (1 == 1) {
int tapcost = power * 3;
std::string way;
std::cout << "type upgrade/buy/a/exit" << std::endl;
std::cin >> way;
if (way == "upgrade") {
std::cout << "1. A Power " << "(Costs: " << tapcost << ")" << std::endl;
int upgr;
std::cin >> upgr;
if (upgr == 1) {
if (0 <= money - power * 3) {
power = power + 1;
money = money - power * 3;
}
else {
std::cout << "You can't afford that!!!" << std::endl;
}
}
}
if (way == "a") {
money = money + power;
}
if (way == "exit") {
break;
}
}
return 0;
}
My updated code. When I run the code it keeps outputting the prices of all the packages instead of just the one I ask for.
#include <iostream>
using namespace std;
int main() {
// to keep it simple
int choice_a = 995;
int choice_b = 1995;
int choice_c = 3995;
char choice;
int message_units, x=1;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice;
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
do{
cout << "How many message units (enter 1 - 672)" << endl;
// again check this
cin >> message_units;
x++;
}
while(x<2);
if(message_units > 5){
choice_a += 100 * (message_units - 5);
}
cout << "Your total cost is " << choice_a /100 << "." <<choice_a%100 endl
if(message_units > 15){
choice_b += 50 * (message_units - 15);
}
cout <<"Yourtotalcostis"<<choice_b /100 << "." << choice_b%100<<endl;
(You missed an "i" or two, but English is difficult for a non-native speaker.)
Atotalcost = 9.95;
if(messageunits>5)
Atotalcost += 1.0 * (messageunits-5);
EDIT:
There are several ways to deal with amounts of money. One of them is to store an amount as a number of cents, then print it out with care. For example, the amount $2.34 is stored as int price = 234, then to print it out we print price/100 (which is 2), then a decimal point, then price%100 (which is 34, the '%' is the modulo operator, you can look it up). So the code will look like this:
#include <iostream>
using namespace std;
int main()
{
int messageunits;
cout << "how many message units(enter 1 - 672)" << endl;
cin >> messageunits;
int Atotalcost = 995; // cost of package a, in cents
if(messageunits > 5){
Atotalcost += 100 * (messageunits - 5);
}
cout << "Your total cost is " << Atotalcost/100 << "." << Atotalcost%100 << endl;
}
There is still much work to do, but this is a good start.
Along those lines, this example may have a few minor errors and I tried to keep it simple.
#include <iostream>
using namespace std;
int main() {
bool finished = false;
do {
// to keep it simple
double choice_a = 9.95;
double choice_b = 19.95;
double choice_c = 39.95;
char choice;
int message_units;
double price;
bool selected = false;
// this loop shows the options initially
do {
cout << "Which package do you choose (enter A, B or C)" << endl;
// you will need to check this
cin >> choice
// keeping it simple
if (choice == 'A') { price = choice_a; selected = true; }
else if (choice == 'B') { price = choice_b; selected = true; }
else if (choice == 'C') { price = choice_c; selected = true; }
cout << endl;
}
// loops until something was selected
while (selected == false);
// user enters how many units is wanted
cout << "How many message units (enter 1 - 999)" << endl;
// again check this (if homework requires checking input)
cin >> message_units;
// Calculating message units
if (message_units > 5) price += message_units * 1;
else price += message_units * 2; // if $2.00 normal?
// Total Price Output
cout << "Total: " << price << endl;
// Is user done?
char done;
cout << "Do you want to enter another? press enter to continue. If you are done, type something and press enter.";
cin >> done;
// check
if (done != '') {
finished = true;
}
}
while (finished = false);
Alright, that is about it. Two do while loops and the rest. There may be some slight errors while compiling, really, you should try to fix those yourself as this is pretty much the entire assignment...
Here I have simple code to serve as a calculator for integers.
//Calculator, by Michael Lowry
#include <iostream>
using namespace std;
void main ()
{
int input = 0;
int input2 = 0;
int answer = 0;
int operation = 0;
cout << "Enter your first number" << endl;
cin >> input;
cout << "Type 1 for addition, 2 for subtraction, 3 for multiplication, or 4 for division" << endl;
cin >> operation;
cout << "Enter your second number" << endl;
cin >> input2;
if (operation = 1)
{
input + input2 == answer;
}
if (operation = 2)
{
input - input2 == answer;
}
if (operation = 3)
{
input * input2 == answer;
}
if (operation = 4)
{
input / input2 == answer;
}
cout << "Your answer is " <<
cout << answer << endl;
system ("PAUSE");
}
When I enter "1" for all three inputs, I get the output "Your answer is 6121DBCC0". Why is my answer variable all messed up?
Your output goes wrong. You should have
cout << "Your answer is " << answer << endl;
instead of
cout << "Your answer is " <<
cout << answer << endl;
What happens is that you are writing the outstream object cout to output.
Also the comparison operators are wrong, as others have noted. You should have == instead of = in the if-statements and vice versa in the assignment part. Like this:
if (operation == 2)
{
answer = input - input2;
}
There are several errors: this is assigning a value to the operation variable, not comparing it against something:
if (operation = 1)
it should rather be
if(operation == 1)
furthermore this doesn't assign the result of input+input2 to answer but rather makes an unused comparison evaluation
input + input2 == answer;
and it should rather be
answer = input + input2;
You should change your code accordingly. Finally this:
cout << "Your answer is " <<
cout << answer << endl;
is wrong since you're passing the cout object along (mind the operator<<). That should have been
cout << "Your answer is " << answer << endl;
Also: main() is supposed to return int.
Thus your code should have looked like:
int main () {
int input = 0;
int input2 = 0;
int answer = 0;
int operation = 0;
cout << "Enter your first number" << endl;
cin >> input;
cout << "Type 1 for addition, 2 for subtraction, 3 for multiplication, or 4 for division" << endl;
cin >> operation;
cout << "Enter your second number" << endl;
cin >> input2;
if (operation == 1) {
answer = input + input2;
}
if (operation == 2) {
answer = input - input2;
}
if (operation == 3) {
answer = input * input2;
}
if (operation == 4) {
answer = input / input2;
}
cout << "Your answer is " << answer << endl;
system ("PAUSE");
}
Try it out
First: Use
if (operation == 1)
instead of
if (operation = 1)
because == is for equality, = is for assignment.
Second:
answer = input1 + input2;
instead of
input + input2 == answer;
Do this in all if statements.
Third: Use
cout << "Your answer is " << answer << endl;
to print your answer.
And remember answer = input / input2 will give you integer division not floating point.
First mistake
If you want to assign value to variable answer you should do:
answer = input1 (required operator here) input2;
In your code such construction:
input - input2 == answer;
Is wrong in 2 ways:
If you want assign value to answer use assigning= not comparing == operator.
Assigning values goes from right to left, so your desired variable should be on the left side.
Second Mistake
In line if (val = yourConstant) you made very popular mistake - assigning inside if statement. Many languages prohibit such things, because they are hard to detect without debuggining or tests. The code inside if statement will be executed only if yourConstant will be more than 0. Instead please use if (val == yourConstant) or if (yourConstant == val).
So instead of:
if (operation = 1)
do:
if (operation == 1)
Also change your output to:
cout << "Your answer is " << answer << endl;
Another mistake:
input - input2 == answer;
This is wrong. You have to make answer equal to input - input2. Also there should only be one =, because it is not a condition.
So:
answer = input - input2;
Apply that to all your arithmetic inside the if statements. That should fix it.
But try to not use system ("PAUSE"); because it has its problems if you transfer your code. Just a suggestion.