The rand() function in C++ is giving a number outside the range - c++

So I'm trying to write a story about Jordan paying bills and stuff. I used a rand function to find a random number for his salary 3.5k - 4.5 and bills 700 -1.5k. I believe I got the formula right but usually, it generates a number outside that area. Below is the code and result.
{
srand(time(NULL));
cout << fixed;
cout << setprecision(2);
float money = 9000;
int minbill = 700;
int maxbill = 1500;
int minsal = 3500;
int maxsal = 4500;
float rent = 3000;
cout << "[Jordan's Balance: Gp" << money << "]\n\n";
cout << "Jordan's rent costs Gp" << rent <<".\n";
float bill = (rand()%maxbill-minbill+1)+minbill;
cout << "Jordan's bills costs Gp" << bill << ".\n";
float totalb = rent + bill;
cout << "Jordan needs to pay a total of Gp" << totalb << "\n\n";
float sal = (rand()%maxsal-minsal+1)+minsal;
cout << "Jordan received a salary of Gp" << sal << "!!\n";
money = money + sal;
cout << "[Jordan's Balance: Gp" << money << "]\n\n";
}
I expect Jordan's bills to be around 700-1.5k and his salary 3.5k-4.5k but it gives me a number below that.
Jordan's rent costs Gp3000.00.
Jordan's bills costs Gp133.00.
Jordan needs to pay a total of Gp3133.00
Jordan received a salary of Gp1906.00!!
[Jordan's Balance: Gp10906.00]

(rand()%maxbill-minbill+1) is wrong.
It's possible that rand()%maxbill will be less than minbill. You need to use rand() % (maxbill - minbill + 1).
float bill = rand() % (maxbill-minbill+1) + minbill;
Similarly, use
float sal = rand() % (maxsal-minsal+1) + minsal;

Related

Don't understand why output is incorrect

I'm currently doing a Zybooks lesson for my C++ class and we're going over while loops. In this question, it wants me to calculate how many years it takes for a bank account to double it's initial balance. There is also an annual contribution added. My code is as follows:
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest + contribution;
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
I used this as an answer but was met with this unexpected result:
Output differs. See highlights below.
Input
100
Your output
Annual contribution:
Year: 13
Balance: 20627.8
Expected output
Annual contribution:
Year: 13
Balance: 20527.8
I see the expected output and your output differs by a 100, i.e. your contribution. Maybe the evaluation system doesn't add annual contribution once your target is reached. The below code gets your required output, but I think your code should have been the correct answer.
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
The problem is that you're making a contribution after the 13th year even though the target has been reached.
I would restructure to something like this, in order to only check the condition once:
while (true)
{
year++;
double interest = balance * RATE / 100;
balance += interest;
if (balance >= TARGET)
{
break;
}
balance += contribution;
}
This is because the last time the loop is being executed (at year=13), balance is less than TARGET but, after adding a contribution and interest into it, it jumps out of the loop with contribution and interest added to it.
So, the solution can be to use an if statement within the while loop to check if it exceeds the TARGET; if it does, then don't add contribution into it.
Replace your while loop with the following:
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}

Creating a tax computing program on c++ , error with uninitialized local variables

First time posting here. Recently started a C++ class and I'm really enjoying it! I'm creating a tax computing program but ran into a bit of wall on this part. I don't know how its not initialized if I already stated it using 'double'
The variable that I'm having trouble with is "taxes2" on line 129
Please help if you can!
Also, this is the prompt im working with:
"Write a program to compute income tax as follows:
First, read the income for the year. Then, display the following menu and ask the user to select his or her filing status:
Single
Married filing separately
Married filing jointly
Head of household
For Single status, apply a deduction of $2000, for #2 $1700, for #3, $2300 and Head of household $2700. Also, ask for and read the number of dependents. Add to the deduction amount, $150 for each dependent up to a maximum of 3 dependents if single, add $125 for each dependent up to a maximum of 4 for Married filing separately, and $175 for each dependent, up to a maximum of 5, if married filing jointly or head of household.
Then, compute the taxable income by subtracting the total deduction computed above from his or her income. Anyone with a taxable income of less than $8,000 pays no taxes. For the rest, the first $15,000 of the income has a tax rate of 10%, the next $25,000 gets taxed at 15%, the next $30,000 at 20%, the next $30,000 at 25% and anything above $100,000 at 30%. So, for example, someone who had taxable income of $125,000, her first $15,000 gets taxed at 10% ($1,500), plus 15% of $25,000 ($3,750), plus 20% of $30,000 ($6,000), plus 25% of $30,000 ($7,500) and the remaining $25,000 at 30% ($7,500) for a total tax amount of $26,250. For someone with income of $13,000, the tax is 10% of that or $1,300. For someone who made $7,999.99 it would be 0, but for someone who made $8,000, it's $800. For someone who made $30,000, it would be 10% of $15,000 or $1,500 plus 15% of the remaining $15,000 or $2,250 making it $3,750, and so on. Display the amount of taxes to be paid."
#include "pch.h"
#include <iostream>
using namespace std;
int main()
{
const double tax1 = 1500.00;
const double tax2 = 3750.00;
const double tax3 = 6000.00;
const double tax4 = 7500.00;
double income;
double istatus;
double itaxes;
double itaxes2;
double ideduction1;
double ideduction2;
double idependant;
const double idependantrate1 = 150;
const double idependantrate2 = 125;
const double idependantrate3 = 175;
double idependanttotal;
cout << "What is your income? " << endl;
cin >> income;
cout << "Please enter your filing status: \n";
cout << "1. Single \n";
cout << "2. Married Filing Separately \n";
cout << "3. Married Filing Jointly \n";
cout << "4. Head of Household \n";
cin >> istatus;
// Begin Deductions
if (istatus == 1)
{
cout << "You've selected Single";
ideduction1 = 2000;
cout << "Please select number of dependants (max: 3): ";
cin >> idependant;
if (idependant >= 0)
{
idependant * idependantrate1 == idependanttotal;
}
idependanttotal + ideduction1 == ideduction2;
}
else if (istatus == 2)
{
cout << "You've selected Married Filing Separately";
ideduction1 = 1700;
cout << "Please select number of dependants (max: 4): ";
cin >> idependant;
if (idependant >= 0)
{
idependant * idependantrate2 == idependanttotal;
}
idependanttotal + ideduction1 == ideduction2;
}
else if (istatus == 3)
{
cout << "You've selected Married Jointly";
ideduction1 = 2300;
cout << "Please select number of dependants (max: 5): ";
cin >> idependant;
if (idependant >= 0)
{
idependant * idependantrate3 == idependanttotal;
}
idependanttotal + ideduction1 == ideduction2;
}
else if (istatus == 4)
{
cout << "You've selected Head of Household";
ideduction1 = 2700;
cout << "Please select number of dependants (max: 5): ";
cin >> idependant;
if (idependant >= 0)
{
idependant * idependantrate3 == idependanttotal;
}
idependanttotal + ideduction1 == ideduction2;
}
// Calculate Income Taxes
if (income <= 7999.99)
{
cout << "No taxes need to be paid. " << endl;
return 0;
}
else if (income >= 8000.00 && income <= 15000.00)
{
itaxes = income * .10; //calculates tax amount
itaxes - ideduction2 == itaxes2;
cout << "The amount owed in taxes is: $" << itaxes2 << endl;
}
else if (income >= 15000.01 && income <= 40000.00)
{
itaxes = ((income - 15000) * .15) + tax1; //calculates tax amount
itaxes - ideduction2 == itaxes2;
cout << "The amount owed in taxes is: $" << itaxes2 << endl;
}
else if (income >= 40000.01 && income <= 70000.00)
{
itaxes = ((income - 40000) * .20) + tax1 + tax2; //calculates tax amount
itaxes - ideduction2 == itaxes2;
cout << "The amount owed in taxes is: $" << itaxes2 << endl;
}
else if (income >= 70000.01 && income <= 100000.00)
{
itaxes = ((income - 70000) * .25) + tax1 + tax2 + tax3; //calculates tax amount
itaxes - ideduction2 == itaxes2;
cout << "The amount owed in taxes is: $" << itaxes2 << endl;
}
else if (income > 100000.01)
{
itaxes = ((income - 100000) * .30) + tax1 + tax2 + tax3 + tax4; //calculates tax amount
itaxes - ideduction2 == itaxes2;
cout << "The amount owed in taxes is: $" << itaxes2 << endl;
}
else
cout << "You have entered an unuseable number. Please restart the program and enter a positive number " << endl;
return 0;
idependant * idependantrate1 == idependanttotal will calculate the value of idependant * idependantrate1, and then check if it equals idependanttotal. If you want to store the calculated value in idependanttotal write idependanttotal = idependant * idependantrate1;.

Looping functions for a number of times

So I am trying to get this program to allow the user to input their data 4 times. I want the program to call each function until the user enters them for the 4th time, but it is not letting me and just stops at the 2nd attempt. Can someone help me with this problem? Thanks!
Output:
Enter the crop name:
Corn
Enter cost, yield, price per bushel, and increase data:
5
5
5
5
Minimum Profit Maximum Profit Average Profit
Corn $20000.00 $145000.00 $82500.00
Enter the crop name:
Enter cost, yield, price per bushel, and increase data:
Peas
Minimum Profit Maximum Profit Average Profit
$20000.00 $145000.00 $82500.00
Enter the crop name:
Enter cost, yield, price per bushel, and increase data:
Minimum Profit Maximum Profit Average Profit
$20000.00 $145000.00 $82500.00
Enter the crop name:
Enter cost, yield, price per bushel, and increase data:
Minimum Profit Maximum Profit Average Profit
$20000.00 $145000.00 $82500.00
Enter the crop name:
Enter cost, yield, price per bushel, and increase data:
Minimum Profit Maximum Profit Average Profit
$20000.00 $145000.00 $82500.00
Press any key to continue . . .
enter code here
Program:
#include <iostream>
#include<iomanip>
#include<string>
#define ACRES 1000;
using namespace std;
//Function prototypes.
void getData(string*, float*, int*, float*, float*);
void calculate(float, int, float, float, float*, float*, float*);
void printResults(string, float, float, float);
int main()
{
string name;
float CostPerAcre, increase, bushel, MinNP, MaxNP, AvgProfit2, bestcrop;
int yield;
for(int i = 0; i <= 4; ++i)
{
getData(&name, &CostPerAcre, &yield, &bushel, &increase);
calculate(CostPerAcre, yield, bushel, increase, &MinNP, &MaxNP, &AvgProfit2);
printResults(name, MinNP, MaxNP, AvgProfit2);
}
//cout << endl << "Old MacDonald, you should plant " << bestCrop << endl << endl;
return 0;
}
// This function allows the user to input their data.
void getData(string *cropname, float *costpa, int *bpa, float *dpb, float *dpbincrease)
{
cout << "Enter the crop name: " << endl;
getline(cin, *cropname);
cout << "Enter cost, yield, price per bushel, and increase data: " << endl;
cin >> *costpa >> *bpa >> *dpb >> *dpbincrease;
}
// This function uses the data to calculate the projected range of net profit and the average net profit for each crop.
void calculate(float costpa, int bpa, float dpb, float dpbincrease, float *MnNP, float *MxNP, float *AvgProfit)
{
float MnGP, MxGP;
float costofCrop = costpa * ACRES;
MnGP = (bpa * dpb ) * ACRES;
MxGP = MnGP + (MnGP * dpbincrease);
*MnNP = (MnGP)-costofCrop;
*MxNP = (MxGP)-costofCrop;
*AvgProfit = (*MxNP + *MnNP) / 2;
}
// This function displays the minimum profit, maximum profit, and average profit.
void printResults(string cropname, float MnNP, float MxNP, float AvgProfit)
{
cout << setw(25) << right << "Minimum Profit" << setw(20) << right << "Maximum Profit" << setw(20) << right << "Average Profit" << endl;
cout << cropname << setw(5) << right << setprecision(2) << fixed << '$' << MnNP << setw(10) << right << setprecision(2) << fixed << '$' << MxNP << setw(10) << right << setprecision(2) << fixed << '$' << AvgProfit << endl;
}
In the getData function, instead of using getline, do:
cin >> *cropname;
Why? Like they said in a similar question, "If you're using getline after cin >> something, you need to flush the newline out of the buffer in between".
insert that after reading from console.
cin.clear();
fflush(stdin);
or
cin.flush();
or
cin.ignore(INT_MAX);
depends on the system you are running it
Check This for more Info

C++ cashier code

The question:
Giving change. Implement a program that directs a cashier how to give
change. The program has two inputs: the amount due and the amount
received from the customer. Display the dollars, quarters, dimes,
nickels, and pennies that the customer should receive in return.
What i have so far:
#include <iostream>
using namespace std;
int main()
{
double amount_due;
double amount_recieved;
cout << "Enter amount due: " << endl;
cin >> amount_due;
cout << "Enter amount received: ";
cin >> amount_recieved;
int change = amount_recieved - amount_due;
int dollar = 100;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
//Return change in full dollars
cout << "dollars: " << change % 100 << endl;
//Return change in quarters
cout << "quarters: " << (change % 100) % 25 << endl;
//Return change in dimes
cout << "dimes: " << ((change % 100) % 25) % 10 << endl;
// Return change in nickels
cout << "nickels: " << (((change % 100) % 25) % 10) % 5 << endl;
//Return change in pennies
cout << "pennies: " << ((((change % 100) % 25) % 10) % 5) % 1 << endl;
system("pause");
return 0;
}
I realize there are some other one of these answered but they may be to advanced to use in my code, what am i doing wrong?
What you want to do is the same as a cashier would do.
First ensure the change is represented as whole pennies.
Then provide enough dollars until the change remaining is less than a dollar. Then move on to quarters, then dimes, nickels and pennies.
So for the dollar case, pseudo-code would be:
dollars = change / 100 # get integral number of dollars
change = change % 100 # and reduce change-left-to-go accordingly
print dollars, " dollars"
It should then be a simple matter to apply that logic to the other coin types in order of reducing value.
There are several problems. The first is that you ask the user to input values, but don't specify what they are. If the user enters a number that's not in pennies, you're not going to get the value you expect. I expect this input should be in dollars. So, first, change change into:
change = int((amount_recieved - amount_due) * 100.0)
Next:
cout << "dollars: " << change % 100 << end;
Will return the remainder of dividing change by 100, which is not what you want. You simply want to divide dollars by 100. You also want to likely modify change to stop you having to repeat this math.
dollars = change / 100;
cout << "dollars: " << dollars << endl;
change -= dollars*100;
From there, the rest of the code should work as expected minus the % 100 parts. As others have mentioned in the comments to the question, your problem is arising from not thinking the math through first, not from doing anything inherently wrong with C++. This would have produced the wrong result in any language, including writing it down as math on a blackboard.
As others have mentioned, you are not doing the step required to get this working, and that is repeated subtraction. Yes, you subtracted the price from the amount given, and determined the dollars to give, but you failed to subtract out those dollars, giving you a new total to determine how many quarters.
Something like this (assuming you're working in pennies):
change_left = customer_payment - original_cost;
//...
number of dollars = change_left / 100;
change_left = change_left - (100 * number of dollars); <-- where is this?
Now how do you determine the number of quarters? You have a "running total" called change_left that is being reduced by the change you currently have given the customer. You repeat similar steps to get the number of quarters, then number of dimes, nickels, etc., i.e. divide by 25, then subtract out the number of quarters giving a new "change_left". Then repeat for 10 to get the dimes, 5 to get the number of nickels, etc.
So again, the problem isn't C++ -- the issue is that you are not thinking this out as a discrete series of steps that lead to a final goal.
#include <iostream>
using namespace std;
int main() {
double amount_due;
double amount_recieved;
cout << "Enter amount due: " << endl;
cin >> amount_due;
cout << "Enter amount received: ";
cin >> amount_recieved;
int change = amount_recieved - amount_due;
int dollar = 100;
int quarters = 25;
int dimes = 10;
int nickels = 5;
int pennies = 1;
//Return change in full dollars
cout << "dollars: " << change / 100 << endl;
//Return change in quarters
cout << "quarters: " << (change % 100) / 25 << endl;
//Return change in dimes
cout << "dimes: " << ((change % 100) % 25) / 10 << endl;
// Return change in nickels
cout << "nickels: " << (((change % 100) % 25) % 10) / 5 << endl;
//Return change in pennies
cout << "pennies: " << ((((change % 100) % 25) % 10) % 5) / 1 << endl;
return 0;
}

How to break a for loop and convert integers?

My program needs to calculates the cost for customers
to replace their carpet at $5 per yard for installation, various padding options,
carpet cost and total all rounded up to the nearest yard.
Padding is cost is based on:
Good - $3 per yard - 1-3year warranty
Better - $4 per yard 3-5 year warranty
Best- $5 per yard - 5-10 year warranty
Excellent - $7 per yard 10-20 year warranty
Operation:
Prompt User for number of rooms For each room:
Prompt length than width for each number of room
Calculate square feet a. convert square feet to square yards and round up b. square yards = yards required for room c. Calculate installation cost by square yard *$5
Prompt user to choose padding. a. Multiply padding cost by square yard of room
Prompt user for carpeting cost per sq yard of room: a. Calculate cost by multiplying input by squareyards required
Output total yards required
Output Installation cost
Output padding cost
Output carpet cost
Output total cost = + Installation + PAdding + Carpet
Grand total = cost of each room
******************/
I have 5 problems so far:
How to convert the integer padding choice to the cost of the quality
The floor loop will not break between rooms
When it displays the room number it starts at 0
How do I get the dollars to display to 2 decimal places?
How will I get the total of each rooms to store as doubles to get the grand total?
#include <iostream>
#include <iomanip>
#include <string>
#include <conio.h>
#include <string>
using namespace std;
const float INSTALL_COST = 5;
const float GOOD_PAD = 3;
const float BETR_PAD = 4;
const float BEST_PAD = 5;
const float EXC_PAD = 7;
const double SQU_FT_YD = 9;
int main ()
{
int padding, rooms, numreq, squareYards;
double length, width, squareFeet,priceSquareYard;
double paddingCost, installFee, totalCost, carpetCost;
//step 1:
cout << "Enter number of rooms: ";
cin >> numreq;
cout << endl;
//Step 2
cout << "Enter length of room: ";
cin >> length;
cout << endl;
cout << "Enter width of room: ";
cin >> width;
cout << endl;
//step 3
cout << "Select quality of padding:<1-4> ";
cout << "\n1. Good - $3 per yard - 1-3 year warranty \n2. Better - $4 per yard 3-5 year warranty \n3. Best- $5 per yard - 5-10 year warranty \n4. Excellent - $7 per yard 10-20 year warranty: ";
cin >> padding;
cout << "Enter price of carpeting per square yard of room: ";
cin >> priceSquareYard;
//step3
for(int x = 0; x < numreq; x++)
{
squareFeet = length * width;
squareYards = ((squareFeet / SQU_FT_YD) + 0.5);
if (squareYards > 0)
squareYards++;
installFee = squareYards * INSTALL_COST;
carpetCost = priceSquareYard * squareYards;
paddingCost = squareYards * padding;
totalCost = carpetCost + installFee + paddingCost;
cout << "\n Room " << x << " Yards Required = " << squareYards;
cout << "\n Room " << x << " Installation = $" <<installFee;
cout << "\n Room " << x << " Padding Cost = $" << paddingCost;
cout << "\n Room " << x << " Carpet Cost = $" << carpetCost;
cout << "\n Room " << x << " Total Cost = $" << totalCost;
}
_getch();
return 0;
}
To get totals within loops, simply store a variable outside of the loop, start it at 0, and increment it within the loop whenever necessary.
And you can use break; to break out of the loop completely. Also, if you need this, continue; will let you stop the current iteration and jump straight to the next iteration of your for-loop.
And for number 4, check this out:
NumberFormat/DecimalFormat treats certain floating-point values as longs instead of doubles