//Purpose: To calculate the price to pay an author
//Programmer: Brandon C Ballard
//Last Updated: 2/20/2014
#include <iostream>
#include <cstdlib>
using namespace std;
//function prototype
float TotalPay(int numWords, char Level);
int main()
{
float TotalPay;
int numWords;
char Level;
int amtToPay;
cout << "Please enter number of words: ";
cin >> numWords;
cout << endl;
cout << "Please enter a Level, A,B, or C: ";
cin >> Level; cout << endl << endl;
//calculate price per word
if (numWords < 7500)
amtToPay = numWords * .08;
else if (numWords >= 7500 && numWords < 8000)
amtToPay = 600;
else if (numWords >= 8000 && numWords < 17500)
amtToPay = numWords * .075;
else if (numWords >= 17500 && numWords < 19000)
amtToPay = 1313;
else
amtToPay = numWords *.07;
//calculate the Level of the author
if (Level == 'C' or Level == 'c')
Level = 1;
else if (Level == 'B' or Level == 'b')
Level = 1.25;
else if (Level == 'A' or Level == 'a')
Level = 1.75;
TotalPay = amtToPay * Level;
cout << "Length of Story (words): "; cout << numWords; cout << endl << endl;
cout << "Amount Due Author: "; cout << "$"; cout << TotalPay; cout << endl << endl << endl;
system("PAUSE");
return 0;
}//end main function
My instructor wants me to write a program that can calculate the amount of money to pay an author who is submitting an article to a magazine. The amount of money to pay the author is based off of how many words are in the article. It works like this...
-if length (in words) is less than 7,500: the author gets paid $0.08 per word.
-if length is 7,500 to 8,000: the author gets paid a fixed $600.
-if length is 8,000 to 17,500: the author gets paid $0.075 per word.
-if length is 17,500 to 19,000: the author gets paid a fixed $1313.
-if length is greater than 19,000: the author gets paid $0.08 per word.
Also: There are three different "Levels" of authors (A,B, and C). A "C" Level author (new author) would get paid based on the information above. A "B" Level author (established writer) would get paid 1.25 times the amount of a Level C author. An "A" Level author (rockstar) would get paid 1.75 times the amount of a Level C author.
The Math: Basically, I wrote the program so that it first calculates the amount to pay the author (amtToPay). Then, it calculates what the (Level) is equal to. Then the (TotalPay) is the (amtToPay) multiplied by the (Level).
My Problem: Everything works great except for the part where it //calculates the Level of the author. For example, if I were to input the author as an "A" Level, he should get paid 1.75 times that of a Level C author. So, it should multiply the (amtToPay) by 1.75, except what is actually doing is multiplying it by "1" and is ignoring the ".75".
I am new to programming and I understand that there are probably many other ways to write this. But please try and help me the best that you can. Thank you.
Level is an integer type so when you assign the floating point numbers to it, the fractional parts are dropped.
Try defining double rateLevel and then
if (Level == 'C' or Level == 'c')
rateLevel = 1;
else if (Level == 'B' or Level == 'b')
rateLevel = 1.25;
else if (Level == 'A' or Level == 'a')
rateLevel = 1.75;
TotalPay = amtToPay * rateLevel;
The proper way to do this is to not use floating point types at all, except maybe for printouts. The way to accomplish this is to scale everything by a power of ten that will remove all fractional components from your values. In your code the least significant digit is in the thousands place (0.075). This means that you need to multiply all your values by 1000. This is called your scale factor. Then you can do your math using only integral types, int, long, int64_t, etc. At the end of your calculations you can split the results into whole number and fractional components.
Like this:
int TotalPayDollars = TotalPay/1000;
int TotalPayMilliDollars = TotalPay - 1000*TotalPayDollars;
int TotalPayCents = (int)((double)TotalPayMilliDollars/10 + 0.5);
The first line is all integer math so the dividing by 1000 discards any fractional parts.
The second line finds the difference between your original value and the truncated value. We multiply TotalPayDollars by 1000 to bring it into the same units as TotalPay again.
In the last line the + 0.5 works to round up to the nearest cent.
NOTE: when choosing a scale factor it is very important to make sure that you don't overflow your integer type. A 32 bit signed integer can only hold numbers up to 2^31-1 (2,147,483,647). If any of your calculations will go higher than that value then you should use a 64 bit integer type.
Level is type char which is integral, you should create a new variable specifically to hold the amount boosted by level:
double level_boost;
//logic
Totalpay = amtToPay * level_boost;
PS: in your logic, you do not have to use &&:
if (numWords < 7500)
amtToPay = numWords * .08;
else if (numWords < 8000)
//if the numwords is less than 7500 will be handled by first if
amtToPay = 600;
Related
I am attempting to develop a vending machine in C++ in which the user can insert as many 50 cent, 20 cent, and 10 cent coins as they would like to then move on to the 'purchase' of a product.
So far, my primitive code runs smoothly; the issue I am currently facing is that I can only 'insert' coins into the vending machine once, even though I think the 'while' condition in the 'do/while' statement is being executed.
Below you can find my code:
`
#include <iostream>
using namespace std;
int main() {
int productid;
string order, finished;
int amount;
cout << "Welcome to the coffee machine! We have a variety of beverages we can offer. \n Here is our selection: \n 1) Coffee- 50 cents \n 2) Tea- 60 cents \n 3) Cappuccino- 80 cents\n";
cout << "Please select your drink of choice by entering its ID: (1, 2, or 3)";
cin >> productid;
if (productid != 1 && productid != 2 && productid != 3){
cout << "That is an invalid entry; please try again. \n";
cin >> productid;
}
cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n ";
cout << "When finished, please input '0'. ";
cin >> amount;
if (amount != 50 && amount != 20 && amount != 10 && amount != 0){
cout << "That is an invalid coin; please insert coins again.\n";
cin >> amount;
}
do {
amount += amount;
}
while (amount != 0);
return 0;
}
`
I was expecting to be able to insert coins until I input '0', but the code terminal says 'Process finished with exit code 0' after I insert coins once, thereby not allowing me to continue to insert coins.
If anyone has any suggestions as to how I could fix this so that the user can continuously insert coins until they input '0' I would greatly appreciate it.
Please feel free to leave any suggestions as to how to proceed as well.
Thank you
Your do-while looks like this:
do {
amount += amount;
}
while (amount != 0);
What does this do? It adds amount to itself until eventually it is 0. This can happen due to the fact that numbers are stored in a finite number of bits in memory and when due to some operation (value assignment in this case) is greater than the maximum value that can be stored for the given type, then the value will overflow its type limits and may get a smaller value than prior to the addition as a result, maybe even 0.
However, this is definitely not what you want.
You want: to read amount repeatedly until it's 0 and add it to a sum
You actually do: read amount exactly once, then add it to itself until it's 0
How to remedy this:
Move the reading inside the code and make sure that the sum will be a different variable:
cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n ";
cout << "When finished, please input '0'. ";
int sum = 0;
do {
cin >> amount;
if (amount != 50 && amount != 20 && amount != 10 && amount != 0){
cout << "That is an invalid coin; please insert coins again.\n";
} else {
sum += amount;
}
}
while (amount != 0);
You need to put the do { ... } while(...); around the entire block you'd like to repeat. Also, you need a separate variable for the sum.
int amount, sum = 0;
// ...
cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n ";
cout << "When finished, please input '0'. ";
do {
cin >> amount;
while (amount != 50 && amount != 20 && amount != 10 && amount != 0){
cout << "That is an invalid coin; please insert coins again.\n";
cin >> amount;
}
sum += amount;
}
while (amount != 0);
I've also changed an if to a while in your code for the case when the user makes multiple mistakes.
To solve these cases yourself, it's recommended that you either use a debugger and step through your code; or add some logging into the code an check what's going on (e.g., what the loop repeats).
the reason why the program does not ask you for another input is because the do-while loop only includes one line: amount += amount;
Also this is the issue why the program terminates, it gets stuck in this loop of adding amount on itself and when the int overflow happens and the amount gets zero value, the program terminates. You can check this behavior by printing out the amount variable in the loop.
amount += amount;
cout << amount << endl;
To fix the issue, you need to move couple of lines inside do block.
do {
cout << "Please insert your coins. \n This vending machine only accepts 50 cent coins, 20 cent coins, and 10 cent coins. \n ";
cout << "When finished, please input '0'. ";
cin >> amount;
cout << amount << endl;
if (amount != 50 && amount != 20 && amount != 10 && amount != 0){
cout << "That is an invalid coin; please insert coins again.\n";
cin >> amount;
}
amount += amount;
cout << amount << endl;
}
while (amount != 0);
Also, you need one more variable for the sum of coins (amount). This way if you add only one coin, the amount variable will be doubled.
Hope this helps.
I'm trying to learn C++ and there is a problem I am trying to work out. Basically I need to calculate the square root of a number. I think I'm on the right track, but when I run the code nothing happens after I input a number.
int n;
double r, intGuess, guess, ratio;
// user input
cout << "Enter number: ";
cin >> n;
intGuess = n;
guess = n / 2;
ratio = intGuess / guess;
while (ratio >= 1.01 || ratio <= 0.99)
{
r = n / guess;
guess = (guess + r) / 2;
}
cout << endl;
cout << "The square root of " << n << " is " << guess << endl;
Your loop seems to be infinite because you never update ratio inside it... then if the condition is true once, it is true forever...
It should be something like:
ratio = intGuess / guess;
while (ratio >= 1.01 || ratio <= 0.99)
{
intGuess = guess; // Save the previous value of guess
r = n / guess;
guess = (guess + r) / 2;
ratio = intGuess / guess; // Update ratio here with the previous and the
// actual value of guess
}
Also:
until guess is within 1% of the previous guess
You should save the previous guess and use this one for your ratio, not the original one.
Live example of this algorithm. I added two lines in the loop.
You are supposed to be comparing the previous guess to the current one. That's not what you are doing.
Example: Suppose you input 4. The first guess is going to be 2, which is the exact value. Every successive guess will also be 2. Even if you update the ratio as IntGuess/guess inside the loop, it's going to be 2. Always.
Fix your code so you are comparing the previous guess and the current one and all will be good.
Hi I'm needing some help. I'm in a intro to programming class and we are using c++. I am hoping someone can help me with an assignment that was due yesterday (I understand not to expect miracle responses but a girl can always try).
I'm having two problems that I know of. The first is regarding the smallest value.
The big one is in trying to make it loop for requirements of three times but not lose out on my total count. I cannot use arrays or anything I haven't learned yet which is why I've posted this. I've seen similar problems and questions but they have ended up with answers too complex for current progress in class. So here is the problems instructions:
Instructions
1) Write a program to find the average value, the largest value, and the smallest value of a set of numbers supplied as input from the keyboard. The number of values in the data set must be in the range 0 to 20, inclusive. The user will first enter the number of values in the data set(use variable int Number). Give the user 3 attempts at entering Number in the range given. If the value for Number entered is out of this range, write an error message but continue. If the user does not enter a valid value for Number within the 3 attempts print an error message and terminate the program.
2) Format only the output for the Average value to 3 decimal places when printed.
3) The values in the data set entered as input can be any value positive, negative, or zero.
4) Make the program output readable(see the example below). (Note: that you will notprint out the input values that were entered in this program like you normally are required to do. This is because we have not covered the “tool” needed to do so yet in our studies).
Below will be the output from the execution of your program:
(using these values in order for the data set --> 19.0 53.4 704.0 -15.2 0 100.0)
The largest number: 704
The smallest number: -15.2
The average of the 6 numbers entered: 143.533
yourName L4p2XX.cpp
Lab#4 prob 2 XX-XX-12
Here is my poor excuse at the solution:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double Number = 0, minValue, maxValue, average, total = 0;
int ct = 0, numCount;
cout << "How many numbers would you like to enter? ";
cin >> numCount;
for(ct = 1; ct <= numCount; ct += 1)
{
cout << "Enter Value from 0 to 20, inclusive: ";
cin >> Number;
if(Number > 20|| Number < 0)
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
{
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
total += Number;
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
} //end for loop
cout << "The smallest number entered was " << minValue << endl;
cout << "The largest number you entered was " << maxValue << endl;
average = total/numCount;
cout << setprecision(3) << fixed << showpoint << "You entered " <<
numCount << " numbers. The average of these is " << average;
//Program ID
cout <<"\n" << "L4P2LB.cpp\n" << "11-05-12\n";
system ("pause");
return 0;
} // End main
Thank you in advance to anyone who can steer me in the right direction. Not looking for anyone to do my work I just need help in direction if nothing else or any suggestions as to what to do. Thanks again. Lynda
Also I need somehow to pause after the third time and exit properly. If I put the second pause in it won't work so am I missing something obvious there too!
The first problem I see is that you didn't initialize a couple of variables.
You should either initialize both minValue and maxValue variables with something which will overwritten in every case in the first loop (typically "positive/negative infinity", as provided by <limits>), or just set both to Number in the first iteration, regardless of their current value. So I'd suggest to fix this by replacing
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
with
if(maxValue <= Number || ct == 1)
maxValue = Number;
if(Number <= minValue || ct == 1)
minValue = Number;
as ct == 1 will be true in the first iteration.
That said, you check the 0..20 range condition on the wrong variable. You check it on the Number variable, but you should check the numCount variable. But you also didn't respect the requirement that the variable to store the "number of numbers" should be Number, so you did check the correct variable, but used the wrong to read the input into. This should fix this issue (I changed the variable name in the cin >>... line + moved the check outside your main loop):
cout << "How many numbers would you like to enter? ";
cin >> Number;
if(Number > 20|| Number < 0)
{
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
...
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
}
for(ct = 1; ct <= Number; ct += 1)
{
...
}
...
I have wrote some basic code for a project. I am at the point I am trying to take an input from a RFID reader using a keyboard emulator. The follwing is my code to this point:
#include <iostream>
#include <ios>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
char product; //declaring the variable for the switch/case
int Pay = 0; //Declaring the variable Pay
int Payment = 0;
double Total = 0; // Declaring the Final Total variable
double Subtotal = 0; // Declaring the variable Subtotal
double Tax = 0; // Declaring the variable Tax
int m = 0; //counts the amount of times milk is scanned
int b = 0; //counts the amount of times beer is scanned
int c = 0; //counts the amount of times candy bar is scanned
int r = 0; //counts the amount of times rice is scanned
cout << "Scan the product you desire to purchase: \n";//Asking user to input product purchasing
cout << "When ready to checkout press the z button.\n\n\n"; //Telling user to press button z to pay
while(Pay < 1) //Keeps in the loop until pay is increased to 1
{
getline(cin, product); //Taking input and assining to the variable product
if(product == E007C02A55EF918D)
{
cout << "6 pack of Budlight...........$6.49\n"; // If the button b is pushed displays
Subtotal = Subtotal + Beer; // Calculates the Subtotal and stores it
Tax = Beer * Taxrate + Tax; // Claculates the total Tax and stores it
b++;
}
else if(product == E007C02A55EF937C)
{
cout << "Snickers Bar.................$0.99\n";// If the button c is pusehd displays
Subtotal = Subtotal + Candy_Bar;
Tax = Candy_Bar * Taxrate + Tax;
c++;
}
else if(product == E007C02A554A7A8B)
{
cout << "1 Gallon of 2% Milk..........$3.99\n";//If the button m is pushed displays
Subtotal = Subtotal + Milk;
m++;
}
else if(product == E007C02A55CE0766)
{
cout << "Box of Brown Rice............$2.79\n";//If the button r is pushed displays
Subtotal = Subtotal + Rice;
r++;
}
else
cout << "Invaild product. Please scan a different product.\n";
if (product == 'z')
Pay++; //When finished it increases pay to 1 to break the while loop
Total = Subtotal + Tax; // Claculates the Total
}
I am using MSVS 2010 to compile this code. With this code I can not compile because it says E007C02A55EF918D is undefined. E007C02A55EF918D is the serial number from one of the RFID tags and is what I am trying to input. I know I am having problems with the getline function also, but I am more worried about getting the serial number as an input.
char is big enough for a single character (it is usually an 8bit quantity, but don't rely on that).
So your product variable can only hold one char.
E007C02A55EF918D is an identifier (because it begins with a letter, it is not considered as a number, and because it is not quoted, it is not interpreted as a string).
If you intended product and those serial numbers to be 64bit numbers, you'll need to change product to be large enough to store them (uint64_t for instance), and change the serial numbers in your code to be numbers by prefixing with 0x. You'll also have to change your input method (getline takes strings, so you will need to convert that string to a number - see How to convert a number to string and vice versa in C++ for instance).
if (product == 0xABCD1234)
If you indented both to be strings, then declare product with:
std::string product;
and quote ("") the serial numbers. You'll also need to change the last test to:
if (product == "z")
^ ^
You can't compare an std::string with a single char ('z' is a char, "z" is a C-style 0-terminated string).
Try having it in "" and use strcmp() instead of ==, like
if (!strcmp("E007C02A55EF937C",product))
or
if (strcmp("E007C02A55EF937C",product)==0)
Hope it helped you.
I need some help revising this. It keeps only displaying 0s as the temp. Thank you.
// A program to determine whether the input number is a perfect number
// A perfect number is defined by the sum of all its positive divisors excluding itself
// 28: 1+2+3+7+14 = 28.
int perfect, limit, divisor;
cout << "Please enter a positive integer in order to define whether it is a perfect integer or not: " ;
cin >> perfect;
cout << endl;
int temp = 0;
int prevtemp = 0;
limit = 1;
divisor = 1;
while (limit < perfect)
{
if ((perfect % divisor) == 0)
{
divisor = prevtemp;
temp = prevtemp + temp;
}
limit++;
divisor++;
}
if (perfect == temp)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
return 0;
You are never setting prevtemp to anything other than 0, so adding it to temp does nothing.
I believe you meant to say
if ((perfect % divisor) == 0)
temp += divisor; // not "divisor = prevtemp;"
The line "temp = prevtemp + temp" should also be removed with this solution; there is no longer any need for the prevtemp variable.
Also, there is no need to keep separate limit and divisor variables, since they are always the same. Just remove limit and change the loop condition to use divisor.
Also, as Mark Byers pointed out, the loop would be simpler to understand if you refactored it into a for loop rather than a while.
It seems like you are making it too complicated. Here's how you could do it:
int total = 0;
for (int i = 1; i < perfect; ++i)
{
if (perfect % i == 0)
total += i;
}
if (perfect == total)
cout << "Your number is a perfect number!" << endl;
else
cout << "Your number is not a perfect number" << endl;
Note that the running total is kept in a variable called total (you called this variable temp) and it is only increased when the number is an exact divisor.
I'm not sure, but I'd guess that in the code:
if ((perfect % divisor) == 0)
divisor = prevtemp;
you intended this to be prevtemp=divisor instead. That fixes an obvious problem, but still leaves quite a bit that doesn't look like it's doing that you probably intended. For example, I can't quite figure out what limit is intended to accomplish -- you initialize it and increment it, but as far as I can see, you never use its value (well, I guess you use it, but its value is always the same as divisor's so I'm not sure why you think you need both, or how limit makes any sense as its name).
Edit: It would make sense to have a limit. In particular, factors always come in pairs: one that's less than or equal to the square root of the number, and one that matches the first that's always greater than or equal to the square root of the number. As such, you don't need to scan all the way up to the number itself looking for factors -- you can set the square root of the number as the limit, and scan only up to that point. For each factor you find up to that point, the matching factor will be perfect/divisor. Since you've already gotten one working example, I guess I might as well just hope this isn't homework, and post an example as well:
bool is_perfect(int number) {
int limit = sqrt((double)number);
int sum = 1;
for (int i=2; i<=limit; i++)
if (number % i == 0)
sum += i + number/i;
return sum == number;
}
You are never assigning anything to prevtemp after initializing it to 0, so there is nothing to add to temp on the line that reads temp = prevtemp + temp.
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int n,i=1,sum=0;
cout<<"Enter a number: ";
cin >> n;
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
cout << i << " is a perfect number";
else
cout << i << " is not a perfect number";
system("pause");
return 0;
}