Adding not multiplying - c++

I am teaching myself C++, starting on the basics have written this:
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string mystr;
int price = 0;
int quantity = 0;
int total = price * quantity;
cout << "------------------------------------------------------" << '/n';
cout << "-----------------Welcome to the shop!-----------------" << '/n';
cout << "------------------------------------------------------" << '/n';
cout << "Enter price of item" << '/n';
getline(cin, mystr);
stringstream(mystr) >> price;
cout << "How Many do you want?" << '/n';
getline(cin, mystr);
stringstream(mystr) >> quantity;
cout << "you want this many: " << quantity << '/n';
cout << "at this price: " << price << '/n';
cout << "this would cost you: " << total << " pounds" << '/n';
if (total >= 20)
{
cout << "here is a discount of " << total / 20 << '/n';
}
else if (total >= 10)
{
cout << "here is a discount of " << total / 10 << '/n';
}
else
{
cout << "sorry no discount" << '/n';
};
}
My only problem is - its adding the total price instead of multiplying. I feel I am missing something very obvious but after an hour I cant seem to find out what it is, I have tried declaring total further down the code which has not worked, I have also tried putting the total in brackets still nothing.
What am I missing?
-- as an example --
10 units at the cost of 10 each, should come out at 100, not 20 as it does on my code

It's not doing anything with the total price, since it'll always be 0.
int total = price * quantity;
The result of the multiplication is performed and "saved" at this point, and doesn't change later even if price and quantity do.
You should put this line after the lines where you truly set the values of price and quantity.
As for your question about "adding not multiplying", with the fix in place as above the value output is correct, so you must be doing something wrong that we can't see. Check that you're running this code, and not some other piece of code.
Also, you've consistently written /n, whereas it should be \n (which further suggests that your screenshot is not from running this code). In fact, the two before your prompt for input should be endl, to ensure that the prompt is flushed to the console.

you are calculating the total at the wrong place.
Initially, you calculate total = price * quantity, with price = 0 and quantity = 0, and this will assign 0 to total. Then after inputting the quantity and price, you do not recalculate the total, so it gives you the wrong result.
My suggestion is to put
total = price * quantity; after stringstream(mystr) >> quantity;

auto total = [&]() { return price * quantity; };
and then use total()
http://coliru.stacked-crooked.com/a/27ba0fa6978ec9e1

Related

C++ code for CS162 class isn't adding user inputs to the total

This code is designed to take an order, add that to the total_price variable, apply discounts based on the total price, then add a tip and echo all the information back to the user.
For some reason when I run the code, it isn't taking input from the user. I think it's related to the while statement but it outputs that my total_price is 0 after entering integers.
The tip calculation at the bottom isn't working correctly. It prompts the user to enter a tip value, but then skips to the end and says the final total is 0, without the user being able to enter any tip.
Thanks so much for the help!!
#include <iostream>
using namespace std;
int main()
{
int total_price{0}; // This variable will contain the price for all orders
int tip{0};
int discount_total{0};
int tip_total = tip + discount_total;
cout << "Welcome!\nThis program is designed to help take your order.\n";
cout << "Our discounts availible today are: \n10 percent off orders over $50, and 5 percent off orders between $25 and $50.\n";
// This is where the user is prompted to enter the price of their order
cout << "Please enter the price of your item: ";
cin >> total_price;
// No negative numbers will be accepted
if (total_price <= 0)
{
cout << "Invalid number, please re-enter the price of your item: ";
}
// User can continue ordering unless typing No
while (total_price > 0)
{
cout << "Is there anything else? If not type No: ";
cin >> total_price;
}
// Once the user types No, it brings them to the tip section
// Marks the end of the order
if ("No")
{
cout << "Thank you. Your total price is " << total_price << endl;
}
// Discount modifications
if (total_price >= 50)
{
discount_total = total_price * .05;
cout << "Your new total is " << discount_total << " with the 10 percent discount.\n";
}
else if (total_price >= 25 && total_price <= 50)
{
discount_total = total_price * .05;
cout << "Your new total is " << total_price << " with the 5 percent discount.\n";
}
else
{
total_price = discount_total;
cout << "Your total is the same, " << total_price << "\n";
}
// Tip calculation
cout << " Feel free to add a tip! Please enter here: ";
cin >> tip;
if (tip > 0)
{
cout << "Your final total is: " << tip_total << " dollars";
}
else if (tip < 0)
{
cout << "Your tip is invalid, please enter a valid tip: ";
}
return 0;
}

input validation and overflow in c++

I'm writing a code that takes a user's input and calculates a discount based on how many units the user buys. Here is my problem; I want to use input validation to make sure the number entered is between 0 and 65535 (the max range for an unsigned int) but the way I have this program set up, if the user enters a number outside of this range I'm experiencing overflow/underflow and an incorrect number is stored in the variable before it ever even hits the if/else clauses. I'm new to C++ so please be kind. What can I do to check if this number is in the correct range when the user enters it. Also, is there a way to verify that the user has not entered a character other than a number?
Here is my code:
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
// display the instructions and inform the user of the discounts available
cout << " This software package sells for $99. Discounts are given according to the following list: \n";
cout << "----------------------------------" << endl;
cout << " Quantity\t\t Discount" << endl;
cout << "----------------------------------" << endl;
cout << " 10 - 19\t\t 20%" << endl;
cout << " 20 - 49\t\t 30%" << endl;
cout << " 50 - 99\t\t 40%" << endl;
cout << " 100 or more\t\t 50%" << endl;
cout << "----------------------------------" << endl;
cout << "\n\n";
const double price = 99.00;
unsigned short quantity; // variable to hold the user's quantity.
// shouldn't need more than 2 bytes for this (unsigned short)
cout << "How many units are sold?: ";
cin >> quantity;
double discount; // variable to hold the amount discounted
double total; // to hold the total sales price
cout << fixed << showpoint << setprecision(2); // set the display of numeric values
// calculate the discounted prices
if (quantity >= 1 && quantity <= 9) {
total = quantity * price; // calculate the total without a discount
cout << "There is no discount for this order \n";
cout << quantity << " units were sold at $" << price << " a piece for a total of " << total << endl;
cout << "\n";
}
else if (quantity >= 10 && quantity <= 19) {
discount = (quantity * price) * .20; // calculate the discount
total = (quantity * price) - discount; // calculate the total
cout << "There is a 20% discount \n";
cout << quantity << " units were sold at $" << price << " with a discount of 20% applied to the order. \n";
cout << "The total cost of the sale is $" << total << endl;
cout << "\n";
}
else if (quantity >= 20 && quantity <= 49) {
discount = (quantity * price) * .30; // calculate the discount
total = (quantity * price) - discount; // calculate the total
cout << "There is a 30% discount \n";
cout << quantity << " units were sold at $" << price << " with a discount of 30% applied to the order. \n";
cout << "The total cost of the sale is $" << total << endl;
cout << "\n";
}
else if (quantity >= 50 && quantity <= 99) {
discount = (quantity * price) * .40; // calculate the discount
total = (quantity * price) - discount; // calculate the total
cout << "There is a 40% discount \n";
cout << quantity << " units were sold at $" << price << " with a discount of 40% applied to the order. \n";
cout << "The total cost of the sale is $" << total << endl;
cout << "\n";
}
else if(quantity > 99 && quantity <= 65535) {
// the maximum number allowed in a short int is 65535. I is unrealistic that someone would order more
// units than that so this else if clause checks to make sure the number of ordered items is below this number
discount = (quantity * price) * .50; // calculate the discount
total = (quantity * price) - discount; // calculate the total
cout << "There is a 50% discount \n";
cout << quantity << " units were sold at $" << price << " with a discount of 50% applied to the order. \n";
cout << "The total cost of the sale is $" << total << endl;
cout << "\n";
}
else {
// the trailing else clause is used to catch any value for quantity that is 0 or below or any quantity
// bigger than what a short int can hold.
cout << "You entered an invalid quantity.\n";
cout << "Please enter a value greater than 0 or less than 65,535. \n\n";
}
system("pause");
return 0;
}
The final else clause is only executed when a value of 0 is entered. Here is an example of the output with a value outside the range
This software package sells for $99. Discounts are given according to the following list:
----------------------------------
Quantity Discount
----------------------------------
10 - 19 20%
20 - 49 30%
50 - 99 40%
100 or more 50%
----------------------------------
How many units are sold?: 65600
There is a 50% discount
52428 units were sold at $99.00 with a discount of 50% applied to the order.
The total cost of the sale is $2595186.00
Press any key to continue . . .
So in all honesty, I don't think this is a bad question.
It just deals with error checking whatever comes out of cin >> quantity.
Like described here: User Input of Integers - Error Handling, a way to handle this is to wrap the cin >> quantity with some error handling code like below.
if (cin >> quantity) {
// read succeeded
} else if (cin.bad()) {
// IO error
} else if (cin.eof()) {
// EOF reached (perhaps combined with a format problem)
} else {
// format problem
}
This will not take care of the integer overflows however, so a full solution would be to make quantity an int and use
cout << "How many units are sold?: ";
if (cin >> quantity) {
// read succeeded
// check for range
if (quantity < 0 || quantity > 65535) {
cout << "Number needs to be between 0 and 65535" << endl;
return -1;
}
} else if (cin.bad()) {
// IO error
cout << "Couldn't do a read from stdin :(" << endl;
return -1;
} else if (cin.eof()) {
// EOF reached (perhaps combined with a format problem)
cout << "Stdin gave EOF :(" << endl;
return -1;
} else {
// format problem
cout << "Encountered incorrect format" << endl;
return -1;
}

C++: Calculations are incorrect when entering a certain input

I've been teaching myself C++ on and off for a few months and now I'm trying to make a payroll system. Here's my code:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void wageCompute (int, int);
int main()
{
int loopTimes=0;
int empNum=100, workHours, otHours, rate, bPay, otPay, grossPay;
string empName, empPos;
cout << "PAYROLL FOR THE MONTH OF MARCH" << endl;
cout << "Employees: " << empNum << endl;
while (empNum>loopTimes)
{
cout << "NAME: ";
cin.ignore();
getline (cin, empName);
cout << "\nPOSITION: ";
getline (cin, empPos);
cout << "\nHOURS WORKED: ";
cin >> workHours;
cout << "\nWAGE PER HOUR: ";
cin >> rate;
bPay = workHours*rate;
cout << "YOUR BASE PAY IS: " << bPay << endl << endl;
cout << "HOURS WORKED OVERTIME: ";
cin >> otHours;
otPay = (1.5*rate)*otHours;
cout << "\nOVERTIME PAY: " << otPay << endl;
grossPay = bPay + otPay;
cout << "GROSS PAY: " << grossPay << endl;
wageCompute(bPay, grossPay);
loopTimes++;
}
return EXIT_SUCCESS;
}
void wageCompute(int bPay, int grossPay)
{
double rate, dedInsurance, dedMedical, totDeduct, netPay, tax;
if (bPay<10001)
{
rate = 0.05;
}
else if (bPay<15001)
{
rate = 0.1;
}
else if (bPay<20001)
{
rate = 0.15;
}
else
{
rate = .2;
}
tax = bPay*rate;
dedInsurance = bPay*0.05;
dedMedical = bPay*0.01;
totDeduct = tax + dedInsurance + dedMedical;
cout << "TAX: " << tax << endl;
cout << "SSS DEDUCTION: " << dedInsurance << endl;
cout << "Medicare DEDUCTION: " << dedMedical << endl;
cout << "TOTAL DEDUCTIONS: " << totDeduct << endl;
netPay = grossPay - totDeduct;
cout << "NET PAY: " << netPay << endl;
}
The part where it goes wrong is when I input a certain value for the Hours Worked, Wage per Hour and Hours worked overtime. The program checks the basic pay for the suitable amount of tax it should deduct, what I input was 160 for the hours worked, 100 for the wage per hour, and 10 for overtime. I've tried lessening and increasing it and it worked just fine it seems that it's just these combination of numbers is the part where it goes wrong.
A screenshot of the output:
Your question isn't very clear but I suspect that what you are seeing here is a well known limitation of floating point numbers; numbers that are easy to represent exactly in base 10 don't have an exact representation in base 2. One example : 0.1 in base 10 is 0.0001100110011… repeating in base 2; the accuracy of the approximation depends on how many bits one is willing to use to write it.
An alternative approach is to use integer arithmetic with a known precision, so say you want to calculate to the nearest hundredth of a penny (I'm using UK currency here). Represent £1.01 as 10100 and when your finished val / 10000 is the pounds and (val % 10000) / 100 is the pence. If needed you can implement some more complex rules around rounding for the pence.

Baseball Batting Average Program

I need help with a program for school. We had to write a program that asks the user for information about a baseball player. We need to calculate the players batting average with their games played, number of times at bat and number of hits. I am running into an issue where my computation for the average is outputting a set number and not performing any computations. I am entering whole integers for all the variables that are used for calculation. So i would input numbers like 1, 4 , 10 etc... As the program stands the value my formula is setting itself equal to is 15903.876. All of my variables used for the average formula are declared as integers and the batting average itself is declared as a double. I have done some debugging my self and found that the computation messes up when it divides the number of times at bat by the number of hits. If anyone could help me figure out the issue i would appreciate it.
//libaries
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
class battingAverage
{
public:
string pName;
int nBats;
int tHits;
int gPlayed;
int gcalled;
double average;
double average1;
double playeraverage;
};
int main()
{
string numberPlayers;
int nplayers;
//enters the number of players the user wants to enter data for
cout << "Enter the number of players you want to enter data for: ";
cin >> numberPlayers;
cout << endl;
//converts the value of numberPlayers to nplayers
istringstream convert(numberPlayers);
//sets integer nplayers equal to the value of the string numberPlayers
if(! (istringstream(numberPlayers) >> nplayers) )
{
nplayers = 0;
}
cout << "This program calculates the batting average of baseball players.\nYou may enter data for " << nplayers << " players." << endl;
battingAverage ba[nplayers];
int index = 0;
//while statement to get data
while(index < nplayers)
{
cout << "Enter the players last name: " << endl;
cin >> ba[index].pName;
cout << "Enter the number of games the player played: " << endl;
cin >> ba[index].gPlayed;
cout << ba[index].gPlayed << endl;
cout << "Enter the number of games the player was called in for: " << endl;
cin >> ba[index].gcalled;
cout << ba[index].gcalled << endl;
cout << "Enter the number of times the player was at bat: " << endl;
cin >> ba[index].nBats;
cout << ba[index].nBats << endl;
cout << "Enter the number of time the player hit: " << endl;
cin >> ba[index].tHits;
cout << ba[index].tHits << endl;
if(ba[index].tHits > ba[index].nBats)
{
cout << "Enter a valid value for the number of times the player hit: ";
cin >> ba[index].tHits;
}
cout << endl;
index++;
}
//rounds average to 3 decimal places
cout << fixed << setprecision( 3 );
//average formula
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
cout << ba[index].playeraverage << endl << endl;//just temp line to check calculation of average.
ba[index].average = .000;
ba[index].average1 = .099;
while(ba[index].average < 1 && ba[index].average1 < .899)
{
ba[index].average +=.100;
ba[index].average1 += .1;
//prints chart
cout << setprecision( 1 ) << ba[index].average << "00" << setprecision( 3 ) << setw(12) << ba[index].average1 << endl;
}
cout << "1.000" << setw(12) << "1.000" << endl;
//version of system pause
cout << "\nPress enter to continue...";
cin.sync();
cin.ignore();
return 0;
}
On this line:
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
You have this expression:
(ba[index].nBats / ba[index].tHits)
Because both nBats and tHits are integers, you're using only integer math.
The answer will be an integer.
For example:
nBats = 10 & tHits = 3, you'd expect the expression to be 3.333.
But it would only be 3
To fix this, I recommend changing to:
((double)ba[index].nBats / ba[index].tHits)
Same thing again with the expression about gPlayed and gcalled.
Your value of index is wrong during the calculations.
I found this as soon as I put your code in a debugger and stepped through it, something you really should have done yourself.
You start with int index = 0;, and increment it as the user puts in each player's data.
At the end of the input-loop, index is now the same as the number of players.
(eg. if you had 5 players, index is now 5, and the player data is stored in ba[0], ba[1], ba[2], ba[3], and ba[4])
Note that at this point ba[5] is NOT valid data. But that is exactly where ba[index] is!
You do all your calculations on ba[index], which is invalid data, and you wonder why you get meaningless results?
I recommend you set index back to 0 before starting your calculations, and make another loop that does the necessary calculations for each player 0...4.

Constant variable multiplied with user input

I've been trying to create a simple program that allows me to display a total score after the user has entered the ammount of successful hits, totalHits, by multiplying that input with the constant variable POINTS resulting in another variable; score.
I didn't think creating such a program would be any problem, but as usual, I was wrong.. When I run the program score is always random, even if I enter '1' as totalHits every time. It can differ from 444949349 to -11189181 to name a couple of examples. I have no idea what I've done wrong, so it would be great if someone could give me a clue as to what to do next :)
Here's the code:
#include <iostream>
using namespace std;
int main()
{
const int POINTS = 50;
int totalHits;
int score = totalHits * POINTS;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
}
Big thanks to KerrekSB and Paddyd for providing me with the correct answer. Here's the finished code with comments:
#include <iostream>
using namespace std;
int main()
{
const int POINTS = 50;
int totalHits;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
/*As you can see I moved the line below from the top of the code.
The problem was I had not properly learned how C++ executes the code.
The orignal code was written in a way that calculates `score` before
the user could decide it's value, resulting in a different total score than
it should have been. In the finished code, the user inputs what
value `totalHits` is, THEN score is calculated by using that value. */
int score = totalHits * POINTS;
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;
}
int totalHits;
int score = totalHits * POINTS;
You are multiplying by an uninitialized variable (totalHits)! You need to apply a value to totalHits before doing this calculation.
Try using the code like this:
const int POINTS = 50;
int totalHits;
int score;
cout << "Please enter the ammount of successful hits: ";
cin >> totalHits;
cout << "You hit " << totalHits << " targets, and your ";
score = totalHits * POINTS; //totalHits has a value here
cout << "score is " << score << " ." << endl;
cin.ignore(cin.rdbuf()->in_avail() + 2);
return 0;