Recently I've started doing Code Chef challenges to practice programming in C and C++ when I came across the ATM challenge. The challenge (which I expected to be relatively easy) was to create a program that withdraws money from a bank account if the withdrawal amount is a multiple of 5 and if the withdraw > balance. If the transaction is accepted it also charges a fee of 0.5, else it just reprints the bank data.
The link to the challenge is here:
https://www.codechef.com/problems/HS08TEST
The program runs perfectly fine for me on my computer but for some reason it is wrong.
Here is my program:
#include <iostream>
#include <cstdio>
#include <iomanip>
using std::cout; using std::cin; using std::endl;
class Bank_data {
private:
double balance;
public:
void withdraw (int amount) {
if (amount > balance - 0.5 || amount % 5 != 0)
printf("%.2f\n", balance);
else
printf("%.2f\n", balance - amount - 0.5);
}
void setBalance (int amount) {
balance = amount;
}
};
int main () {
Bank_data bd;
int withdraw, init_val;
cin >> std::fixed;
cin >> std::setprecision(2) >> withdraw >> init_val;
bd.setBalance (init_val);
bd.withdraw (withdraw);
return 0;
}
Sample io:
I: 5 500
O1: 494.50
I2: 600 500
O2: 500.00
I3: 4 500
O3: 500.00
Related
I am currently working on a prototype payroll system.
Every time I put the required information for the calculations, it always outputs the wrong information (I always check with a calculator).
It doesn't have any errors or warnings so I think the problem is how I format the code.
Can someone please teach me how to fix this problem?
Note: The program is incomplete.
#include <iostream>
#include <vector>
#include <fstream>
#ifdef _WIN32
#include <windows.h>
#define SYSERROR() GetLastError()
#else
#include <errno.h>
#define SYSERROR() errno
#endif
struct Employees//Not in use yet
{
std::string first_name;
std::string last_name;
};
class Salary_variables
{
public:
long days = 0;
long overtime = 0;
long basic_pay = 537;
long overtime_pay = 80.1375;
long regular_salary = days * basic_pay;
long compute()//constructor for determining the employee's salary
{
if (overtime == 0)
{
return regular_salary;
}
else if (overtime >= 0)
{
long overtime_salary = overtime * overtime_pay;
return regular_salary + overtime_salary;
}
}
};
int main()
{
Employees employee;
std::cout << "Type in employee's full name:\n";
std::cin >> employee.first_name >> employee.last_name;
Salary_variables variables;
std::cout << "Type in total amount of days worked:\n";
std::cin >> variables.days;
std::cout << "Type in total amount of overtime hours worked:\n";
std::cin >> variables.overtime;
std::cout << "Total salary: " << variables.compute() << "\n";
return 0;
}
I can see 2 big mistakes in your code, but without examples of input and output it is possible I missed more.
The biggest error is that you are using long - which is an integer type!
You need to use double so that the decimal part of the salary will be preserved in the calculation.
For example, using long 10 hours of overtime would be worth 80 * 10 = 800.
But, with the correct calculation using double, 80.1375 * 10.0 = 801.375.
Also, as others already mentioned, you must do the multiplication inside the compute function.
Member variable initialization happens only once when you create an instance of the class.
So your code multiplies the salary by 0 on line Salary_variables variables;.
If you change the days variable afterwards, nothing will happen.
The below initialization should be done inside compute function:
long regular_salary = days * basic_pay;
Otherwise, it will initialize the variable with default values when creating class variable.
#include <iostream>
#include <cmath>
using namespace std;
/* FINDS AND INITIALIZES TERM */
void findTerm(int t) {
int term = t * 12;
}
/* FINDS AND INITIALIZES RATE */
void findRate(double r) {
double rate = r / 1200.0;
}
/* INITALIZES AMOUNT OF LOAN*/
void findAmount(int amount) {
int num1 = 0.0;
}
void findPayment(int amount, double rate, int term) {
int monthlyPayment = amount * rate / ( 1.0 -pow(rate + 1, -term));
cout<<"Your monthly payment is $"<<monthlyPayment<<". ";
}
This is the main function.
int main() {
int t, a, payment;
double r;
cout<<"Enter the amount of your mortage loan: \n ";
cin>>a;
cout<<"Enter the interest rate: \n";
cin>>r;
cout<<"Enter the term of your loan: \n";
cin>>t;
findPayment(a, r, t); // calls findPayment to calculate monthly payment.
return 0;
}
I ran it over and over again, but it still gives me the incorrect amount.
My professor gave us an example that goes like this:
Loan=$200,000
Rate=4.5%
Term: 30 years
And the findFormula() function is supposed to produce $1013.67 for the mortgage payment. My professor gave us that code as well (monthlyPayment = amount * rate / ( 1.0 – pow(rate + 1, -term));). I'm not sure what's wrong with my code.
The formula may be fine, but you are not returning, nor using, any value from your conversion functions, so its inputs are wrong.
Consider this refactoring of your program:
#include <iostream>
#include <iomanip> // for std::setprecision and std::fixed
#include <cmath>
namespace mortgage {
int months_from_years(int years) {
return years * 12;
}
double monthly_rate_from(double yearly_rate) {
return yearly_rate / 1200.0;
}
double monthly_payment(int amount, double yearly_rate, int years)
{
double rate = monthly_rate_from(yearly_rate);
int term = months_from_years(years);
return amount * rate / ( 1.0 - std::pow(rate + 1.0, -term));
}
} // end of namespace 'mortgage'
int main()
{
using std::cout;
using std::cin;
int amount;
cout << "Enter the amount of your mortage loan (dollars):\n";
cin >> amount;
double rate;
cout << "Enter the interest rate (percentage):\n";
cin >> rate;
int term_in_years;
cout << "Enter the term of your loan (years):\n";
cin >> term_in_years;
cout << "\nYour monthly payment is: $ " << std::setprecision(2) << std::fixed
<< mortgage::monthly_payment(amount, rate, term_in_years) << '\n';
}
It still lacks any checking of the user inputs, but given the values of your example, it outputs:
Enter the amount of your mortage loan (dollars):
200000
Enter the interest rate (percentage):
4.5
Enter the term of your loan (years):
30
Your monthly payment is: $ 1013.37
The slightly difference from your expected output (1013,67) could be due to any sort of rounding error, even a different overload of std::pow choosen by the compiler (since C++11, the integral parameters are promoted to double).
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.
I am facing an error, that is a presentation error. Being a beginner to c++ , I am stuck on the following question:
Two cars (X and Y) leave in the same direction. The car X leaves with a constant speed of 60 km/h and the car Y leaves with a constant speed of 90 km / h.
In one hour (60 minutes) the car Y can get a distance of 30 kilometers from the X car, in other words, it can get away one kilometer for each 2 minutes.
Read the distance (in km) and calculate how long it takes (in minutes) for the car Y to take this distance in relation to the other car.
Input:
30
Output:
60 minutos (minutes in portuguese)
Now, upon submitting the code it says presentation error. Could someone help me find a solution to this error. Thank you in advance.
My code:
#include <iostream>
using namespace std;
int main(){
int Y;
cin >> Y;
cout << 2*Y << " minutos " << endl;
return 2*Y;
}
PE is a common error in OJ of ACM. you can check space , newline charactor or something you missed. for example:
#include <iostream>
using namespace std;
int main(){
int Y;
cin >> Y;
cout << 2*Y << " minutos (minutes in portuguese)" << endl;
return 0;
}
you can have a try, good luck for you.
To fix your problem try to return zero as the main function should return it, if your code is clear from errors.
Try to follow that convention to always return 0 in main.
Your code should look like this:
#include <iostream>
using namespace std;
int main()
{
int Y;
cin >> Y;
cout << 2*Y << " minutos " << endl;
return 0;
}
To conclude simply use cout instead of return.
So, I have to do a homework problem that entails the following:
During the tax season, every Friday, J&J accounting firm privides assistance to people who prepare their own tax returns. Their charges are as follows.
a. If a person has low income (<=25,000) and the consulting time is less than or equal to 30 minutes, there are no charges; otherwise, the service charges are 40% of the regular hourly rate for the time over 30 minutes.
b. For others, if the consulting time is less than or equal to 20 minutes, there are no service charges; otherwise, service charges are 70% of the regular hourly rate for the time over 20 minutes.
(For example, suppose that a person has low income and spent 1 hour and 15 minutes, and the hourly rate is $70.00. Then the billing amount is 70.00 x 0.40 x (45 / 60) = $21.00.)
Write a program that prompts the user to enter the hourly rate, the total consulting time, and whether the person has low income. The program should output the billing amount. The program must contain a function that takes as input the hourly rate, the total consulting time, and a value indicating whether the person has low income. The function should return the billing amount. The program may prompt the user to enter the consulting time in minutes.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
const int HOUR = 60;
int minutes = 0;
double intake(payment);
void intake()
{
char income, y('y'), n('n');
cout << "Is the income rate over 25,000? Y - Yes | N - No): ";
cin >> income;
switch(income)
{
case 'n':
case 'N': low_procedure()
break;
case 'y':
case 'y': high_procedure()
break;
default: cout << "Invalid entry. You must indicate low or high income.\n"
break;
}
}
int main()
{
intake();
cout<<"You owe: \n";
cout<< payment <<endl;
}
double low_procedure()
{
const double LOW_DISCOUNT = 0.40;
const int LOW_TIME = 30;
consult = getConsultTime()
rate = getRate()
if consult > LOW_TIME
{
minutes = consult - LOW_TIME
result = rate * LOW_DISCOUNT
payment = calcPay
}
else
cout <<"No additional fees. \n";
return payment;
}
double high_procedure()
{
const double HIGH_DISCOUNT = 0.70;
const int HIGH_TIME = 20;
consult = getConsultTime()
rate = getRate()
if consult > HIGH_TIME
{
minutes = consult - HIGH_TIME
result = rate * HIGH_DISCOUNT
}
else
cout<<"No additional fees.";
}
int getConsultTime()
{
int consult = 0;
cout << "How long was the consult for in minutes? \n";
cin >> consult;
return consult;
}
double getRate()
{
double rate = 0.00;
cout << "What was the hourly rate? \n";
cin >> rate;
return rate;
}
double calcPay
{
double payment = 0.00;
payment = result * (minutes/HOUR);
return payment;
}
I've been having a lot of trouble here since I realized that I need to declare variables in code. I have a feeling I'm making this more complex than it needs to be, but the switch statement is important. I'm trying to sieve through bad, unimportant data.
You should declare them in the smallest scope that makes sense. Since you are apparently using them in multiple functions, the file scope (which is generally thought of as 'globally', not 'locally') seems appropriate.
As an alternative, you could make a class that has the variables and functions as members, but under the circumstances it seems overkill...
One way to do this is to group data into a struct, make a instance of that struct for each person, and make all functions accept a pointer or a reference of that struct and access its fields.
(When you learn classes then you can forget about this answer.)
There are a lot of reasons to avoid global variables (like namespace pollution).
Even if you limit them to file scope or namespace scope, there are still a lot of reasons to avoid variables with static storage duration (like thread safety, initialization order).
The rule of thumb is always "to use the smallest scope possible".
#include <iostream>
using namespace std;
struct AccountData {
int consult;
int minutes;
double rate;
double result;
double payment;
};
AccountData makeAccount(int consult, int minutes, double rate, double result, double payment)
{
return AccountData({consult, minutes, rate, result, payment});
}
void high_procedure(AccountData *thisAccount)
{
cout << "do something with the account, like printing out \"payment \""
<< thisAccount->payment
<< "\n";
}
void low_procedure(AccountData *thisAccount)
{
thisAccount->payment+=1.0;
cout << "do something with the account, like adding 1 to \"payment \""
<< "\n";
}
int main() {
AccountData account1 = makeAccount(1,2,3,4,5);
high_procedure(&account1);
low_procedure(&account1);
high_procedure(&account1);
AccountData account2 = makeAccount(10,20,30,40,50);
high_procedure(&account2);
low_procedure(&account2);
high_procedure(&account2);
return 0;
}
Demo:
https://ideone.com/sWVoHF