Why are all of my booleans setting off as true? - c++

I tested my code out by printing the values out to see why it did not output the value I should be getting. And I found out all of my booleans that were for the string ride were set off as true and I can not seem to get a clue why. I have tried searching the internet up yet I could not find anything. My understanding of the code is not deep enough for me to understand what is going wrong here.
#include <iostream>
#include <string>
using namespace std;
int main() {
//declarations
string ride;
char comp;
int age;
double td, tp, god, rp, sp, ta, tap;
bool fer, bump, zip, pir, test;
//print outs and input
cout<<"What ride would you like to buy a ticket for? "<<endl;
getline(cin, ride);
cout<<"How old are you?"<<endl;
cin>>age;
//functions
//ride
if (ride == "Ferris Wheel"){
rp = rp + 75.00;
fer = true;
}
if (ride == "Bumper Cars"){
rp = rp + 50.00;
bump = true;
}
if (ride == "Zipper"){
rp = rp + 100.00;
zip = true;
}
if (ride == "The Pirate Ship"){
rp = rp + 75.00;
pir = true;
}
//age
//ferris wheel
if (fer = true){
if (age >= 0 && age <= 7){
cout<<"Do you have a companion that is at least 18 years old? Y/N";
cin>>comp;
if (comp == 'Y'){
td = td + .20;
}
else{
cout<<"You need a companion that is at least 18 years old.";
}
}
else if (age >= 8 && age <= 12){
td = td + .10;
}
else if(age >= 13 && age <= 20 ){
td = td + 0.08;
}
else if(age > 20 && age < 60){
td = td + 0.05;
}
}
//bumper car
if(bump = true){
if (age >= 0 && age <= 7){
cout<<"Do you have a companion that is at least 18 years old? Y/N";
cin>>comp;
if (comp == 'Y'){
td = td + .20;
}
else{
cout<<"You need a companion that is at least 18 years old.";
}
}
else if (age >= 8 && age <= 12){
td = td + .10;
}
else if(age >= 13 && age <= 20 ){
td = td + 0.08;
}
else if(age > 20 && age < 60){
td = td + 0.05;
}
else if(age > 60){
td = td + .20;
}
}
//zipline
if (zip = true){
if (age >= 0 && age <= 7){
cout<<"Do you have a companion that is at least 18 years old? Y/N";
cin>>comp;
if (comp == 'Y'){
td = td + .20;
}
else{
cout<<"You need a companion that is at least 18 years old.";
}
}
td = td + 0.10;
}
// pirate ship
if (pir = true){
if (age >= 0 && age <= 7){
cout<<"Do you have a companion that is at least 18 years old? Y/N";
cin>>comp;
if (comp == 'Y'){
td = td + .20;
}
else{
cout<<"You need a companion that is at least 18 years old.";
}
}
else if (age >= 8 && age <= 12){
td = td + .10;
}
else if(age >= 13 && age <= 20 ){
td = td + 0.08;
}
else if(age > 20 && age < 60){
td = td + 0.05;
}
}
// maths jaajbjabjabjaj B(
cout<<fer<<endl;
cout<<bump<<endl;
cout<<zip<<endl;
cout<<pir<<endl;
cout<<td<<endl;
cout<<rp<<endl;
cout<<td<<endl;
god = rp * td;
cout<<"discount computed: "<<god<<endl;
sp = rp - god;
cout<<"sub pirce jajagnkfgdf: "<<sp<<endl;
tap = sp * 0.05;
cout<<"tap: "<<tap;
ta = sp + tap;
cout<<"ta: "<<ta;
}
input for ride: The Pirate Ship
input for age: 9
output i get from code:
discount i get from code: 30
partial price : 45
total price : 47.25
output i should be getting from code:
discount i get from code: 7.5
partial price : 67.5
total price : 70.875

I think this is because you didn't initialize your boolean variables. There is no single line, where you set "false". So that, they get random values, i.e. any non-zero value is considered as "true".

Set default value for booleans bool fer = false, bump = false, zip = false, pir = false, test = false;
You are using if wrong.
if (zip = true) // if zip equals true.
if (zip == true) // if zip equals true?
Use else if
//ride
if (ride == "Ferris Wheel"){
rp = rp + 75.00;
fer = true;
}
else if (ride == "Bumper Cars"){
rp = rp + 50.00;
bump = true;
}...
The ride cannot equal "Ferris Wheel" and "Bumper Cars" same time.

Related

Get minimum water level of dam without loop

I was given a problem. In the problem I am suppose to take input current month, current year and current water level of a dam from user. There is a scale that from month march to august the water level increase by 150 feet each month and from sep to feb it decreases by 200 feet. Now I am supposed to tell in which month and year the Dam will have no water or 0 feet water level. I have made the below program using loops but I have to it with out loops/recursive function. I got the year by dividing the water level with avg_decrease in water level.You cans see the program that does what I want with loop.
#include<iostream>
using namespace std;
int main(){
int c_month, c_year, wlevel, avg_decrease;
cout<<"Enter current month number: ";
cin>>c_month;
cout<<"Enter current water level: ";
cin>>wlevel;
cout<<"Enter current year: ";
cin>>c_year;
avg_decrease = 300; //-25 each month, -300 each year
cout<<wlevel/avg_decrease<<endl;
int m = c_month, level = wlevel, y = c_year;
while(true){
if(x)
break;
for(int i =0;i<=12;i++){
if(level < 0){
x = true;
break;
}
else if(m >= 3 && m<=8){
level = level +150;
m++;
}
else{
level = level -200;
if(m == 12)
m=1;
else
m++;
}
}
y++;
}
cout<<y<<"\t"<<m<<endl;
}
I want to get the month and year in which the water level is 0 feet which is being printed in the last line without using the loops. I dont know how to implement the above program without using loops. If any one can help, it would be great.
Thanks in advance
test this and change code if my logic is wrong
#include<iostream>
using namespace std;
int main(){
int m, y, lev;
cout << "Enter current month number: ";
cin >> m;
cout << "Enter current year: ";
cin >> y;
cout << "Enter current water level: ";
cin >> lev;
int avg_year = 300; // average year decrease
int year_count = lev/avg_year; // how many entire years we will be decreasing for sure
lev = lev % avg_year; // how much level we still have after entire years have pass
if ((lev > 0) && (m <= 8) && (m >=2)) // march - aug we are adding +150 each month
{
int delta = (6 - m + 2); // how much times we should add +150
lev = lev + 150*delta;
m = m + delta;
}
if((lev > 0) && (m == 8)) // end of aug (sep = -200)
{
m++;
lev = lev - 200;
}
if((lev > 0) && (m == 9)) // end of sep (oct = -200)
{
m++;
lev = lev - 200;
}
if((lev > 0) && (m == 10)) // end of oct (nov = -200)
{
m++;
lev = lev - 200;
}
if((lev > 0) && (m == 11)) // end of nov (dec = -200)
{
m++;
lev = lev - 200;
}
if((lev > 0) && (m == 12)) // end of dec (jan = -200)
{
m = 1;
year_count++;
lev = lev - 200;
}
/*
in case at the beginning of the program m== 1 AND Level == (801 - 899)
2 years past and we are at m == 1 with level == (201 - 299)
februarry gives -200. So at the end of m==2, level == (1 - 99)
when we do march-december we gain +100 level
so in the beginning of the next year jan level will be 101-199
and since jan takes -200 from level. It is definitely next years jan
so we are just increasing year count
*/
if((lev > 0) && (m == 1)) // enf of jan (feb = -200)
{
lev = lev - 200;
if(lev <= 0)
m++;
else
year_count++;
}
cout << (y + year_count) << "\t" << m << endl;
}
UPD
this is bellow I think the right solution as I would do it with all the loops. I doubt it can be achieved just by plain code with no loops or recursion
#include<iostream>
using namespace std;
int level_func(int m, int y, int lev)
{
int ar[] = { -200, -200, 150, 150, 150, 150, 150, 150, -200, -200, -200, -200 };
int m_count = 0;
while (lev > 0)
{
m++;
m_count++;
if (m > 12)
m = 1;
lev = lev + ar[m - 1];
}
return m_count;
}
int main() {
int m, y, lev;
cout << "Enter current month number: ";
cin >> m;
cout << "Enter current year: ";
cin >> y;
cout << "Enter current water level: ";
cin >> lev;
int month_count = level_func(m, y, lev);
y = y + month_count / 12;
m = m + month_count % 12;
if (m > 12)
{
y++;
m = m - 12;
}
cout << y << "\t" << m << endl;
}
I worked on the solution myself and found a very efficient way to do it. I calculated total months required and got the total years from the month.The code is below
#include<iostream>
using namespace std;
int main(){
int exact_months,year = 0;
int c_month, c_year, wlevel, avg_decrease;
cout<<"Enter current month number: ";
cin>>c_month;
cout<<"Enter current water level: ";
cin>>wlevel;
cout<<"Enter current year: ";
cin>>c_year;
int mn;
exact_months = wlevel/25;
mn = (c_month+exact_months)%12;
if ((c_month+exact_months)%12 !=0 && c_month != 1)
year = 1;
year = exact_months/12+year;
cout<<"Date: "<<year+c_year<<":"<<mn;
}

C++ program sometimes giving wrong answer

I have this program, which should give me the smallest original price of the item based on the input from the user.
There are some conditions, for example, if the quantity of the mask is more than 9 the price will be discounted by 10%, 15% if its more than 30 and 20% if it's more than 50. The result should give the answer Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int mprice; //price input
int mquantity; //quantity input
int n; //first input
int fee = 2000; //const fee
float finalprice;
float maskCalc(int price, int quantity) {
float holder = (float)(price - fee) / (float)(quantity);
if (quantity > 0) {
finalprice = holder;
}
//if between 10 and 30
else if (quantity > 9) {
finalprice = holder / 0.9;
}
//between 30 and 49
else if (quantity > 30) {
finalprice = holder / 0.85;
}
//more than 50
else if (quantity > 49) {
finalprice = holder / 0.8;
}
//less than ten
else {
finalprice = holder;
}
return finalprice;
}
int main()
{
cin >> n;
float arr[n];
// Input oruulah loop
for (int i = 0; i < n; i++) {
cin >> mprice >> mquantity;
x = maskCalc(mprice, mquantity);
arr[i] = x;
}
for (int i = 1; i < n; i++) {
if (arr[0] > arr[i]) {
arr[0] = arr[i];
}
}
printf("%.2f", arr[0]);
return 0;
}
I gave the input
3
5000 3
7000 10
3000 1
the answer was 555.56 which is correct, but when I give something like
3
2500 1
7000 10
3000 1
it is giving me 0.00 while I was expecting this to give me 500.00. Any help will be appreciated.
You need to check for the highest quantity first in your if-else switch, otherwise you always fall into the default (<10) case.
//more than 50
if (quantity >= 50) {
finalprice = holder / 0.8;
}
//between 30 and 49
else if (quantity >= 30) {
finalprice = holder / 0.85;
}
//if between 10 and 30
else if (quantity >= 10) {
finalprice = holder / 0.9;
}
//less than ten
else {
finalprice = holder;
}

Multiplying by a decimal wont give me a decimal answer to feed back into my variable

Currently using Clion to work on a homework question. I believe i am using my if-statements correctly, as-well as the double and char but it doesn't seem to be giving me the outcome i seek. The question asks:
Buy one get one half off promotion: the lower price item is half price.
If the customer is club card member, additional 10% off.
Tax is added.
I have tried to move brackets around. I have declared the .90 to a set variable and tried multiplying that but still always gives me the same answer. I think it has something to do with my if-statemets.
using namespace std;
int main() {
double price1, price2, taxRate, fullSubtotal;
char clubCard;
double basePrice, cardPrice, finalPrice;
// ...
cout<<"Enter price of first item: ";
cin>>price1;
cout<<"Enter price of second item: ";
cin>>price2;
cout<<"Does customer have a club card? (Y/N): ";
cin>>clubCard;
cout<<"Enter tax rate, e.g. 5.5 for 5.5% tax: ";
cin>>taxRate;
fullSubtotal = price1 + price2;
taxRate /= 100;
taxRate += 1;
if (price1 > price2) {
price2 /= 2.00;
basePrice = price1 + price2;
if (clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else (clubCard == 'n' || clubCard == 'N'); {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
}
else {
price1 /= 2.00;
basePrice = price1 + price2;
if ((clubCard == 'y') || (clubCard == 'Y')) {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else ((clubCard == 'n') || (clubCard == 'N')); {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
}
cout<<"Base price: "<<fullSubtotal<<endl;
cout<<"Price after discounts: "<<cardPrice<<endl;
cout<<"Total price: "<<finalPrice<<endl;
return 0;
}
Each time i enter the values for each price( 10 and 20), it gives me the correct fullSubtotal, but when i seek the corresponding cardPrice for that route (if-statement), it gives me 25. With a total price (including tax) to be 27.0625. I was expecting the output to be, cardPrice: 22.5 with finalPrice: 24.35625
Your problem is in the else sections:
if(clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
} else
(clubCard == 'n' || clubCard == 'N');
{
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
The condition you tried to add for the else becomes a statement and the code in the {} block after overwrites the values you previously set. Fix:
if(clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
} else if(clubCard == 'n' || clubCard == 'N') {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
Your mistake is at the inner else clause.
An else-clause has no condition, so the (clubCard == 'n' || clubCard == 'N'); is useless, but still correct c++. It evaluates to a bool that is then discarded. The problem is, that the the block after this is always executed, because it has no condition anymore.
Either use else if and drop the semicolon or just drop the whole condition and the semicolon:
...
if (clubCard == 'y' || clubCard == 'Y') {
cardPrice = basePrice * .90;
finalPrice = taxRate * cardPrice;
}
else {
cardPrice = basePrice;
finalPrice = taxRate * cardPrice;
}
....

c++ bad access error on find()

I am getting a bad access error while trying to find days between two dates given as a string. I found that the maximum number of days that my function will find is 1884 but I don't know why. The bad access error is in the a.find("/") function call.
Here is the code. Any help would be much appreciated, thanks.
int daysBetweenDates(string a, string b) {
if (a == b) {
return 0;
}
cout << a << endl;
int month = stoi(a.substr(0, a.find("/")));
a = a.substr(a.find("/")+1);
int day = stoi(a.substr(0, a.find("/")));
a = a.substr(a.find("/")+1);
int year = stoi(a);
int k = 0; // days in the month;
if (month == 2) {
k = year%4==0 ? 29 : 28;
}
else if ((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
k = 30;
}
else {
k = 31;
}
day++;
if (day > k) {
month++;
day = 1;
}
if (month > 12) {
year++;
month = 1;
}
string new_a = to_string(month) + "/" + to_string(day) + "/" + to_string(year);
return 1 + daysBetweenDates(new_a, b);
}
The recursive calls are eventually causing a stack overflow. Change the code to remove the potentially deeply nested calls. For example, by changing the routine to use a loop. C++ compilers typically do not do tail recursion optimization.

Variable not initialized in C++ code?

Edit: Thank you all very much for your answers, I know now that this was a stupid question, but I've been attempting to get into C++ after just getting a handle on Visual Basic, so a lot of these things I am unfamiliar with. I promise I'm not just asking them to waste your time.
I've been trying to do a sample project in C++ to learn the basics, and I'm having an issue with the current code. The program is supposed to add up user inputted variables and take into account which month they have entered to apply different charges. However, It says that my variable, usageCost, hasn't been initialized. Here's the code:
#include <iostream>
using namespace std;
int main()
{
string monthtext;
double month,
days,
hours,
kwhr,
completeCharge,
energyadjustCharge;
const double flatservicecharge = 5.31;
cout << "Enter the month (1-12) :";
cin >> month;
cout << "Number of days in the period :";
cin >> days;
cout << "Kilowatt hours used :";
cin >> hours;
if (month = 1){
monthtext = "January";
}
else{
if (month = 2){
monthtext = "February";
}
else{
if (month = 3){
monthtext = "March";
}
else{
if (month = 4){
monthtext = "April";
}
else{
if (month = 5){
monthtext = "May";
}
else{
if (month = 6){
monthtext = "June";
}
else{
if (month = 7){
monthtext = "July";
}
else{
if (month = 8){
monthtext = "August";
}
else{
if (month = 9){
monthtext = "September";
}
else{
if (month = 10){
monthtext = "October";
}
else{
if (month = 11){
monthtext = "November";
}
else{
if (month = 12){
monthtext = "December";
}
}
}
}
}
}
}
}
}
}
}
}
double usageCost;
if (month <= 5 && month >= 10 && hours <= 500){
usageCost = hours * 12.9266;
}
if (month <= 5 && month >= 10 && hours > 500){
usageCost = 500 * 12.9266 + (hours - 500) * 10.9917;
}
if (month >= 6 && month <= 9 && hours <= 750){
usageCost = 750 * 12.9266;
}
if (month >= 6 && month <= 9 && hours > 750){
usageCost = 750 * 12.9266 + (hours - 750) * 14.2592;
}
energyadjustCharge = hours * .1305;
completeCharge = usageCost + flatservicecharge + energyadjustCharge;
cin.get();
return 1;
}
You declare:
double usageCost;
but as you can see, you don't set it to any value, thus it is unintialized.
Compiler is correct.
Solution:
Try:
double usageCost = 0.0;
Edit 1:
Other Issues with your program:
Assignment uses "=", comparison uses "=="
Please change all your if statements accordingly.
Replace if statements with array lookup
Adding the following will simplify your program:
const std::string month_names[] =
{"No month index 0",
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
};
// ...
month_text = month_names[month];
The error is because you have some code paths that never set usageCost. Rather than hide the error by initializing usageCost, it is better to fix your code which surely did intend to give usageCost a value in all cases.
In fact it is good that you didn't initialize usageCost because it meant you got a compiler warning to alert you to the later logic error.
month <= 5 && month >= 10 is never true. No month is before June and also after September. You probably meant (month <= 5 || month >= 10). The brackets are important because you have another && condition following.
However it would be better to avoid code duplication and avoid the possibility of none of the four cases being entered by rewriting that section:
if ( month >= 6 && month <= 9 )
{
if ( hours > 750 )
usageCost = ......;
else
usageCost = ......;
}
else
{
if ( hours > 500 )
usageCost = ......;
else
usageCost = ......;
}
With this structure it is impossible for usageCost to not be assigned something.
You have defined month to be a double.
double month;
cout << "Enter the month (1-12) :";
cin >> month;
If I type 5.5 for this input, you can see that usageCost will never be initialized to any value.
double usageCost;
// This will evaluate to false
if (month <= 5 && month >= 10 && hours <= 500){
usageCost = hours * 12.9266;
}
// This will evaluate to false
if (month <= 5 && month >= 10 && hours > 500){
usageCost = 500 * 12.9266 + (hours - 500) * 10.9917;
}
// This will evaluate to false
if (month >= 6 && month <= 9 && hours <= 750){
usageCost = 750 * 12.9266;
}
// This will evaluate to false
if (month >= 6 && month <= 9 && hours > 750){
usageCost = 750 * 12.9266 + (hours - 750) * 14.2592;
}
Consider:
Initializing usageCost to a default value
using an int or similar for values that will only ever be "whole numbers".
using month > 5 as the true inverse of month <= 5
I fixed a number of issues for you.
#include <iostream>
using namespace std;
int main()
{
string monthtext;
double month,
days,
hours,
kwhr,
completeCharge,
energyadjustCharge;
const double flatservicecharge = 5.31;
cout << "Enter the month (1-12) :";
cin >> month;
cout << "Number of days in the period :";
cin >> days;
cout << "Kilowatt hours used :";
cin >> hours;
struct {int input; string month;} Calendar[] = {
{ 1, "January" },
{ 2, "February" },
{ 3, "March" },
{ 4, "April" },
{ 5, "May" },
{ 6, "June" },
{ 7, "July" },
{ 8, "August" },
{ 9, "September" },
{ 10, "October" },
{ 11, "November" },
{ 12, "December" } };
for(int i = 0; i < ARRAY_SIZE(Calendar); ++i)
{
if (month == Calendar[i].input)
{
monthtext = Calendar[i].month;
break;
}
}
double usageCost = 0.0;
if (month <= 5 && month >= 10 && hours <= 500)
{
usageCost = hours * 12.9266;
}
if (month <= 5 && month >= 10 && hours > 500)
{
usageCost = 500 * 12.9266 + (hours - 500) * 10.9917;
}
if (month >= 6 && month <= 9 && hours <= 750)
{
usageCost = 750 * 12.9266;
}
if (month >= 6 && month <= 9 && hours > 750)
{
usageCost = 750 * 12.9266 + (hours - 750) * 14.2592;
}
energyadjustCharge = hours * .1305;
completeCharge = usageCost + flatservicecharge + energyadjustCharge;
cin.get();
return 0;
}