Attempting to construct a milage calculator - c++

I am attempting to construct a mileage calculator. The design is like this,
If a person drives 100 miles or less then the amount they shall be paid 25 cent per mile.
If a person drives in excess of 100 miles, they shall be paid the initial 25 cents for their first 100 miles in addition to 15 cents for every mile over 100 mile...
So an example would be
10 miles would earn the person a dollar, while 250 miles would earn (25 for the first 100 + 22.50 for the second 150) to a grand total of 47.50..
When I hit start without debugging, the program goes to the black screen to put values in. But then I receive an error message.. I am trying to figure out what it means.
I am using microsoft visual studio 2008. C++ coding.
#include <iostream>
using namespace std;
int main()
{
int varOne ;
cout << "Enter your favorite number" << endl;
cin << varOne << endl;
if(varOne <= 100)
cout << (1/4)*(varOne)<< endl;
if (varOne>= 100)
cout << (.15 * (varOne-100)) + (.25 * 100) <, endl;
return 0;
}
Debug Error!
Program ... isual Studio
2008\Projects\practice\Debug\rorioodweorrfhur.exe
Module: ... isual studio
2008\Projects\practice\Debug\rorioodweorfhur.exe
File:
Run-Time Check Failure #3 - The variable 'var1' is being used without being initialized.
(Press Retry to debug the application)

Here are some simple errors I noticed in your code
cin << varOne << endl;
It should be
cin >> varOne ;
Next error
cout << (.15 * (varOne-100)) + (.25 * 100) <, endl;
This should be
cout << (.15 * (varOne-100)) + (.25 * 100) << endl;
Here are some logical errors.
In your If statements, you are checking >= and <= , Check for equality only once. Change
if(varOne <= 100)
to
if(varOne < 100)
Also change
cout<< (1/4)*(varOne) << endl;
to
cout<< (varOne)/4 << endl;
This is because 1/4 will give 0

Related

How can I calculate the total pay for this assignment?

I am trying to write this assignment for school where the program has to calculate the regular pay, overtime pay and total pay separately. I would like to also include a statement where it mentions that if the number entered by the user is negative, the program would tell the user that the number entered is invalid so I have added it but it but it shows an error on the "else if" line. Im also trying to add a function where it calculates the total pay for the user but I don't know how to do it.
this is my code
#include <iostream>;
#include <iomanip>;
using namespace std;
int main ()
{
double hoursworked, hourlyrate, regularpay, overtimepay, totalpay;
int MIN_HOURSWORKED = 1,
MIN_HOURLYRATE = 1;
cout << "type in how many hours have you worked this week.\n";
cin >> hoursworked;
cout << "type in your hourlyrate.\n";
cin >> hourlyrate;
if (hoursworked < MIN_HOURSWORKED && MIN_HOURLYRATE < 0)
{
if (40 > hoursworked)
regularpay = hoursworked * hourlyrate;
cout << "your regular pay is : $ " << regularpay << endl;
else if (hoursworked > 40)
overtimepay = (hoursworked - 40) * 1.5 * hourlyrate;
cout << " your overtime pay is: $" << overtimepay << endl;
}
else
{
cout << "you entered an invalid number.";
cout << "please enter a number that is bigger than 0" << endl;
}
return 0 ;
}
Here are the code changes I made and the comments explain why
#include <iostream>
using namespace std;
int main()
{
//By initializing hoursworked and hourlyrate as negative, it ensures that the while loops used in the cin is used at least once
double hoursworked=-1, hourlyrate=-1, regularpay, overtimepay, totalpay;
int MIN_HOURSWORKED = 1,
MIN_HOURLYRATE = 1;
cout << "type in how many hours have you worked this week.\n";
//Until hoursworked is positive the loop will keep running
while(hoursworked<0)
{cout<<"Enter a positive value"<<endl; cin >> hoursworked;}
//Until hourlyrate is positive the loop will keep running
cout << "type in your hourlyrate.\n";
while(hourlyrate<0)
{cout<<"Enter a positive value"<<endl; cin >> hourlyrate;}
//Your previous code (hoursworked<MIN_HOURSWORKED
//&& MIN_HOURLYRATE<0) ensures that hoursworked is lesser than
//min_hoursworked and that min_hourlyrate is less than 0. Which
//Im sure is not what you want to do
if (hoursworked>MIN_HOURSWORKED && hourlyrate>MIN_HOURLYRATE)
{
if (40>hoursworked)
{
regularpay = hoursworked * hourlyrate;
cout << "your regular pay is : $ " << regularpay << endl;
}
else if (hoursworked>40)
{
overtimepay = (hoursworked - 40) * 1.5 * hourlyrate;
cout << " your overtime pay is: $" << overtimepay << endl;
}
}
else
{
cout << "you entered an invalid number.";
cout << "please enter a number that is bigger than 0" << endl;
}
return 0;
}
The way you make a function is explained well HERE
Also the reason why you were getting errors in your if and else if because of brackets {}. As a new coder, use {} everywhere even when it seems like you don't need to. It is good practice and helps keep a lot of confusions at bay
P.S. Please accept my answer if you find it useful as that would help me get some reputation points
An if clause with two or more statements requires braces to be used:
if ( /* condition */ )
{
statement;
statement;
...
}
The omission of the braces means that only the first statement after the if statement "belongs" to it:
if (40 > hoursworked)
regularpay = hoursworked * hourlyrate;
That's the entire if statement, and nothing else. A few lines below, an else if appears out of nowhere. Your compiler gets confused, and complains about it.
Your outermost if statement already includes these braces, so you simply forgot to use them here.
Although this will solve the compilation error, the resulting code will still not work right, for at least three reasons.
An hoursworked of exactly 40 will not meet either of the if conditions, and nothing will be printed.
An hoursworked in excess of 40 will not meet the first if's condition, so the first message does not get printed. This seems to be a rather obvious mistake.
The outermost if condition gets met only if both of these are true:
if (hoursworked < MIN_HOURSWORKED && MIN_HOURLYRATE < 0)
If you read this verbatim, this means: do all if the following are all true: hoursworked is less than the minimum allowed, and the hourly rate is negative. So, if someone would enter -5 hours worked, and an hourly rate of -10, this condition will be met. This will be considered valid input, and the statements inside this if statement will execute, otherwise the input is rejected as invalid.
That, also, is obviously incorrect.
So, in addition to fixing the compilation error, you will also need to make additional changes to your program, in order to correct all of these defects. Good luck.

My current code isn’t running properly in MS Visual Studio?

I am working on a project for the office today and I’m running into a bit of a stumble today on it. My code is properly debugged but it when ran it ignores all the parameters I set up and becomes smashed all together in a one line executable (if that makes sense). Here’s the prompt and what I have so far:
“A business needs to calculate the bonus points for sales representatives. The bonus points are based on how much each sales representative sold the year.
Write a program to prompt the user to enter the sales amount for a sales representative. Include different functions for each group of Sales representatives.
Display the bonus points as integers.
Please see the table showing the Groups, Sales, and Bonus points:
Groups Sales Bonus points:
A $0 - $100, 000 500 points
$100, 001 - $1,000,000 1, 500 points
B $1,000,001 - $2,000, 000 2,000 points
$2,000,001 - $3,000, 000 2, 500 points
C $3,000,001 - $4,000, 000 3, 000 points
$4,000,001 and over 5, 000 points
Input Validation: Do not accept negative numbers for sales.”
And here’s what I have tried so far:
#include <iostream>
#include <iomanip>
using namespace std;
float salesamounts; //sales made
int username; // Sales rep name
int main()
{
cout << “Please enter your sales made for the year: $”
cin >> salesamounts;
cout << endl;
// exception on program
if (salesamounts <= -1);
{
if (salesamounts <= -1);
cout << “Value cannot be negative. Please input again.”
}
// Group A placement
for (;salesamount <= 100000;)
{
if ((salesamounts <= 100000)
cout << “Congratulations! You earned 500 Bonus Points!”
break;
{
for (; salesamounts > 100001 < 1000000;)
{
if ((salesamounts > 100001 < 1000000));
cout << “Congrats! 10000 Bonus Points have been credited to you!”
break;
}
According to your requirement, you could use if-elseif-else to judge each group of Sales representatives, which is like:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double salesamounts; //sales made
int username; // Sales rep name
cout << "Please enter your sales made for the year : $" << endl;
while (cin >> salesamounts) {
// exception on program
if (salesamounts < 0.0) {
cout << "Value cannot be negative.Please input again." << endl;
}
//judge salesamounts
else if (salesamounts>0.0 && salesamounts <= 100000.0) {
cout << "Congratulations!You earned 500 Bonus Points!" << endl;
}
else if (salesamounts > 100000.0 && salesamounts <= 1000000.0) {
cout << "Congrats!1500 Bonus Points have been credited to you!" << endl;
}
else if (salesamounts > 1000000.0 && salesamounts <= 2000000.0) {
cout << "Congrats!2,000 Bonus Points have been credited to you!" << endl;
}
else if (salesamounts > 2000000.0 && salesamounts <= 3000000.0) {
cout << "Congrats!2,500 Bonus Points have been credited to you!" << endl;
}
else if (salesamounts > 3000000.0 && salesamounts <= 4000000.0) {
cout << "Congrats!3,000 Bonus Points have been credited to you!" << endl;
}
else if (salesamounts > 4000000.0 ) {
cout << "Congrats!5,000 Bonus Points have been credited to you!" << endl;
}
else {
break;
}
}
}
By the way, you could also use switch statement to do this.
You did the input part almost correctly, but after that you confused the if-else-if part with for loops.
When taking the user input, you can use a while loop to check whether the value is negative or not. This will make the program to prompt the user to enter a value again if the entered value does not match the criteria:
float salesamounts;
cout<<"Enter the sales amounts for the year:"; //the program will prompt the user initially
cin>>salesamounts; //user inputs the value here
while(salesamounts<0) //this line checks if the value is negative, if yes, it'll continue running this block till the value is non-negative
{
cout<<"Negative numbers not allowed. Please enter again: "; //Suppose the value is negative. Then the program will display this line and prompt the user to enter again
cin>>salesamounts; //user enters the value again
}
The next step in your program is to then check the user input and make the program act accordingly. The if-else statement will do that perfectly:
if (salesamount<=100000) //checks the value. If this is true, then then the following line will run. Else, the program will move to the next check.
cout<<"Bonus point is 500"; //displays the output if the above condition is correct
else if (salesamount<=1000000) //second check
cout<<"Bonus point is 1500"; //displays if the second condition is true
.
.
.
else
cout<<"Bonus point is 5000";
and so on.
Just to clarify, a loop is used only when you want a particular block of code to run repeatedly, whereas, to check or compare two values, you use the if-else statement.
Note that I've not written the second check as if (salesamounts>=100001 && salesamounts<=1000000) and also, I gave the last check as only else, not else if.

How do I calculate and display the correct percentage?

I am a C++ noob.
I am trying to work on this text-based game for school, and I am having trouble with displaying the correct percentage. I think this has to do with how I calculate it in the program, or I am screwing something up with the function.
I would be most grateful for some assistance. Cheers.
#include <string>
#include <cmath>
#include <iostream>
using namespace std;
double menu (float crew_count);
double calculatePct(float crew_count, float number_of_deaths)
{
double percent = ((crew_count - number_of_deaths) / crew_count) * 100;
}
double welcome ()
{
int crew_count;
string backstory = "\nYou are in charge of a top-secret military mission, when your\nspace ship makes an emergency landing, on the largest moon of planet Gork.\nThe space ship is damaged. Oxygen levels begin to drop.\nHow many military personnel are on your ship?\nNumber of personnel: ";
cout << backstory;
cin >> crew_count;
if (crew_count >= 1)
menu(crew_count);
else if (crew_count < 1)
cout << "\nThere must be 1 or more members of the crew! Please enter a valid number!\n";
}
double menu (float crew_count)
{
double percent;
double main_option;
cout << "\nChoose one:\n1. Attempt repairs on the ship.\n2. Request an emergency rescue from mission command.\n3. Break protocol and reveal the top-secret space ship's location,\nto the Russians on a nearby moon, asking for their assistance.\nYour choice: ";
cin >> main_option;
if (main_option == 1)
{
cout << "\nToxic material on the moon has corroded the launch gear, and the \nlaunch exploded!\n\nThere were no survivors.\n";
}
else if (main_option == 2)
{
cout << "\nThe oxygen was depleted before the rescue team arrived.\nThere were 4 people killed.\n";
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
}
else if (main_option == 3)
{
cout << "\nThe Russians agree to send a rescue ship, but secretly attempt to hack into the ships systems remotely, which triggers an automatic shut down of all\ncommunications systems and locks all mission critical storage units, including\none of the storage unit that holds emergency oxygen tanks.\n\nOne quarter of all personnel are lost.\n";
}
else if (main_option != 1, 2, 3)
{
cout << "\nYou have been eaten by a Grue!\n";
}
}
int main()
{
cout << "Welcome to Gork 1.0\nCreated by Cortez Phenix\nTo make selections, enter the number of each option!\n\n";
int choice;
cout << "What would you like to do?\n1. Play Game\n2. Exit\nYour Choice: ";
cin >> choice;
if (choice == 1)
welcome();
else if (choice == 2)
cout << "\nGoodbye!\n";
else
cout << "\nPlease choose 1 or 2.\n";
return 0;
}
Excuse me. I'm sure this post is hectic.
IMAGE: At the bottom, you can see the queer number
If we do some slight reformatting on parts of your code, it looks like this:
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
The value you print is not the value calculated by calculatePct, it's the indeterminate value of the percent variable defined earlier in the function.
In short: You forgot your curly-braces:
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
{ // Note curly brace here
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
} // And also here
I recommend you enable more verbose warnings, as the compiler should be able to detect that you use the uninitialized variable, as well as the new variable being initialized but not used.
you mixed intergers and floats and void
int crew_count then you fed double menu(float crew_count).
your menu function doesnt return anything its supossed to be void so does your welcome function
Also you calculatePct does not return the calculated percentage. Do that by adding return percent;
See if it helps

calculate x years for savings with deposition and revenue C++

I'm sitting with a challenging homework in C++ and would be really thankful for some help here!
My program need to calculate how many years it will take for an optional yearly deposition with revenue to reach a specific savings limit.
I just can't see what's wrong and have tried debugging with no help.
It doesn't really help neither that i'm totally new to C++ and MVS 2015.
I don't know if it's the math or the programming itself that is wrong.
Static typing is foreign to me since I usually use python.
Also VS don't give much information and the program just stops after asking for revenue input.
Any suggestions?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
int deposit;
int max_savings;
double revenue;
double change_factor;
double year = 0;
double geometric_sum;
cout << "Choose a yearly deposition:\n";
cin >> deposit;
cout << "Set your max saving-goal:\n";
cin >> max_savings;
cout << "set a revenue in percent:\n";
cin >> revenue;
change_factor = 1 + (revenue / 100);
geometric_sum = ((double)deposit * (pow(change_factor, year) - 1)) / (change_factor - 1);
while (geometric_sum < max_savings)
year++;
cout << "Your saving-goal will be in " << year << " years!" << endl;
cout << "Your account balance will then be " << geometric_sum << " dollars!" << endl;
return 0;
}
pow(change_factor, year) - 1
year is set to 0. Any value at the power of 0 is 1. 1 - 1 = 0. Basically you are multiplying with 0.

C++ Finding square root without sqrt function loop glitching

So I am making this as a homework assignment. I understand that there are so many ways that this code could be more efficient and accurate but this is the way my professor wants it done.
I am having problems with the loop. When I ask for the square root of 67 it does find it but it loops the correct answer 3 times.
Enter a value to be square rooted:
67
33.5
guess = 17.75
guess = 10.7623
guess = 8.49387
guess = 8.19096
guess = 8.18535
guess = 8.18535
guess = 8.18535
The program took 7 guess to find an estimation.
When I try to find the square root of 5 it finds it but continues to loop indefinitely
using namespace std;
int main()
{
double guess2;
double squarenumber;
double guess1;
int numofguess = 0;
cout << "Enter a value to be square rooted: " << endl;
cin >> squarenumber;
guess1 = squarenumber/2;
cout << guess1 << endl;
do
{
guess2 = (guess1 - (((guess1 * guess1) - squarenumber)/(2* guess1)));
guess1 = guess2;
cout << "guess = " << guess2 << endl;
numofguess = numofguess + 1;
} while ((guess2 * guess2) > squarenumber);
cout<< "The program took "<< numofguess <<" guess to find an estimation.";
return 0;
}
I think that what you are missing is a proper exit condition.
Your code is written to loop indefinitely until the guess is "perfect".
You should have an exit condition checking if current guess is the same as previous guess, which obviously means that you won't do any better.
Here is my suggestion based on your code :
using namespace std;
int main()
{
double guess2;
double squarenumber;
double guess1;
int numofguess = 0;
cout << "Enter a value to be square rooted: " << endl;
cin >> squarenumber;
guess2 = guess1 = squarenumber/2;
cout << guess1 << endl;
const double epsilon = squarenumber * 1E-6;
do
{
guess1 = guess2;
guess2 = (guess1 - (((guess1 * guess1) - squarenumber)/(2* guess1)));
cout << "guess = " << guess2 << endl;
numofguess = numofguess + 1;
} while ((guess2 * guess2) > squarenumber && fabs(guess2-guess1) > epsilon);
cout<< "The program took "<< numofguess <<" guess to find an estimation.";
return 0;
}
Mickaël C. Guimarães's answer is basically correct, check for an episolon value (absolute difference from the correct answer and your answer). But the "(guess2 * guess2) > squarenumber" should be dropped completely. That's because the value could in theory overshoot and be too low. The algorithm actually goes upwards if the value is too low. e.g. if you want SQRT(25) and your "guess1" prediction is way too low at 2, then guess2 would equal
(2 - (((2 * 2) - 25)/(2* 2))) = 7.25;
And on the next iteration then falls to 6.725624, so heads in the right direction. Low values actually get boosted up and eventually approach the target. By stopping if the value drops below the true SQRT then you might get "false positives" where too low values are accepted as accurate enough.
The times when the system got "stuck" were basically like the story Acchiles and the Tortoise. At each step, the system was dividing the remaining distance to go by some amount, but the change was therefore smaller each step, and could in theory never converge on the exact value, therefore you decide how much accuracy you want so that it finishes in a set time.
Additionally, the issue where the system seemed to take too many steps to converge is because floating point numbers are stored in higher precision, but cout has limited display precision. You can control that by sending setting values to cout before the print commands:
std::cout << std::fixed; // force all values to show to the same decimals
std::cout << std::setprecision(6); // set how many places to show
These code can be streamed to cout in one command before the value to print as well:
std::cout << std::fixed << std::setprecision(6) << "guess = " << guess2 << endl;