C++ overloading addition not working correctly - c++

So basically I'm trying to overload the plus operator so that it adds up change in price1 (1, 99) and price2 (2, 99). So 1.99 + 2.99 should equal 4.98 dollars. The code compiles, but I almost have the answer. Instead of 4.98, it gives out 3.1.98, which is not right. How can I fix this? I'm open to any suggestions or ideas
Here's my header file, titled MyClass.h:
#pragma once
class MyClass
{
public:
int bills;
double coins;
MyClass (int, int);
double sum () { return (bills + (coins * 0.01)); }
MyClass operator+ (MyClass);
MyClass(void);
~MyClass(void);
};
and my source file:
#include <iostream>
#include <string>
#include "MyClass.h"
using namespace std;
MyClass::MyClass(void)
{
}
MyClass::~MyClass(void)
{
}
MyClass::MyClass(int d, int c)
{
bills = d;
coins = c;
}
MyClass MyClass::operator+ (MyClass param) {
MyClass temp;
temp.bills = bills + param.bills;
temp.coins = (coins + param.coins) * 0.01; //Here is the problem, I think
return temp;
}
void main()
{
MyClass price1 (1, 99);
MyClass price2 (2, 99);
MyClass total;
total = price1 + price2;
cout << total.bills << "." << total.coins << endl;
}

You have converted coins in sum () already.
update
temp.coins = (coins + param.coins) * 0.01;
to
temp.coins = coins + param.coins;
And output statement is wrong, you print . by yourself
cout << total.sum() << endl;

Curious as to why you're using a double for pennies. You don't usually have fractions of a pennies except when paying for gasoline, so int would make more sense.
A few things of note:
As aforementioned, be sure to do only temp.coins = coins + param.coins;.
You're not transferring the value of the pennies, just the number of pennies.
Also, carry over pennies! 199 cents is 1 dollar 99 cents. This should translate into something like
int totalCoins = coins + param.coins;
temp.bills = bills + param.bills + totalCoins / 100;
temp.coins = totalCoins % 100;
assuming that you've turned coins into an int.
And by the way, you're not dumb. Every master was once a beginner.

you should update
temp.bills = bills + param.bills;
temp.coins = (coins + param.coins) * 0.01;
TO
temp.bills = bills + param.bills + (coins + param.coins) / 100
temp.coins = (coins + param.coins) % 100
by the way, coins should be int type

Related

Need help to solve and find the weekly pay accordingly

The problem is in the screenshot.
And this is my code and my approach. But the results are off, I think the hour values and the rate value is the pay_rate function is not updated accordingly.
#include <iostream>
#include <stdio.h>
float pay_rate(float, float*);
float total_pay(float, float, float*);
int main() {
float h, rate, total_salary = 0;
printf("Input worked hours: ");
scanf("%f", &h);
pay_rate(h, &rate);
// printf("%f", rate);
total_pay(h ,rate,&total_salary);
printf("\n%f", total_salary);
}
float pay_rate(float hour, float* rate) {
float temp = 0;
if (0 < hour && hour <= 40)
{
*rate = 12.5;
hour = (hour)-40;
// printf("\n%f", hour)/;
} else if (0 < hour && hour <= 4) {
*rate = 15;
hour = hour-4;
// printf("\n%f", *hour);
} else if (hour > 0) {
*rate = 20;
// printf("\n%f",*hour);
}
return *rate;
}
float total_pay(float hours, float rate, float* salary){
*salary = rate * hours;
return *salary;
}
When I input 41 hours, the result is 820. But the result has to be 40*12.5 then +1*15 which equals 515.
You misunderstood the question. And therefore even your manually expected output is wrong.
First you need to calulate a base salary rate, which is only dependent on the category A or B or C or D.
The category is an input parameter. It must be read by read from the user (A or B or C or D) and then the base salry rate is fixed.
Then, depending on the worked hours, part (and only part) of the hours over a given threshold, will be multiplied with a factor.
So, if it is over 44, then only the hours over 44 will be multiplied with 2. The numbers above 40 and less/equal than 44 will be multiplied by 1.5. And the hours bgetween 0 and 40 will be paid with the base salary rate.
In simple C++ you could write something like this:
#include <iostream>
// Get the pay rate based in the pay category
double pay_rate(const char payCategory) {
double result = 0;
if (payCategory == 'A')
result = 12.5;
else if (payCategory == 'B')
result = 15;
else if (payCategory == 'C')
result = 20;
else if (payCategory == 'D')
result = 25;
else
std::cerr << "\n*** Error: Invalid Pay Category\n\n";
return result;
}
// Calculate the toal weekly pay based on pay category and hours worked
double total_pay(const char payCategory, const unsigned int hours) {
// The result
double pay = 0;
// Get base hourly rate
double hourlyRate = pay_rate(payCategory);
// Was the working time more than 44 hours?
if (hours > 44)
pay = (hours-44) * hourlyRate * 2 + 4 * hourlyRate * 1.5 + 40 * hourlyRate;
// NOt more than 44. Maybe more than 40?
else if (hours > 40)
pay = (hours-40) * hourlyRate * 1.5 + 40 * hourlyRate;
else
// Just in the range of 0-4ß
pay = hours * hourlyRate;
return pay;
}
int main() {
// Give user instruction. Enter Pay Category and number of hours worked
std::cout << "Enter payment category (one of A,B,C,D) and number of hours worked:\n";
// Get input from user and validate it
char payCategory = '\0';
unsigned int hours = 0;
if ((std::cin >> payCategory >> hours) and (payCategory=='A' or payCategory=='B' or payCategory=='C' or payCategory=='D'))
// Input was valid. SHow result
std::cout << "\n\n\nTotal salary: " << total_pay(payCategory, hours);
else
std::cerr << "\n\n*** Error: Invalid Input\n\n";
}
.
.
With a littel bit more advanced approch we would made the code data driven. Meaning, you just give the data, so the category data and the range data.
With that, you can simply modify values and the logic and code will be the same.
See for example this:
#include <iostream>
#include <map>
std::map<char, double> salaryByCategory {{'A', 12.5}, {'B', 15}, {'C', 20}, {'D', 25}};
std::map<unsigned int, double> overtimeFactor{{0,1},{40,1.5},{44,2}};
int main() {
// Give user instruction. Enter Pay Category and number of hours worked
std::cout << "Enter payment category (one of A,B,C,D) and number of hours worked:\n";
// Get input from user and validate it
char payCategory = '\0';
unsigned int hours = 0;
if ((std::cin >> payCategory >> hours) and salaryByCategory.count(payCategory) == 1) {
// Get base salary based on category
double baseSalary{salaryByCategory[payCategory]};
// This is the resulting payment that we will output at the end
double payment{};
// Calculate total payment
for (auto riter = overtimeFactor.rbegin(); riter != overtimeFactor.rend(); ++riter) {
// If we are above an upper border
if (hours > riter->first) {
// Calculate hours that are above the max threshold
const unsigned int hoursAbove = hours - riter->first;
// Payment for this range
payment += (hoursAbove * riter->second * baseSalary);
// New hours (without the already calculated one)
hours -= hoursAbove;
}
}
// Show result
std::cout << "\n\nResult: " << payment << '\n';
}
else
std::cerr << "\n\n*** Error: Invalid Input\n\n";
}

How do I update ELO ratings after a certain number of games played?

I have a list of games played between two FIFA 19 players and wish to use that data to update my ELO ratings between the two players, according to the games played. I am trying to use this data to constantly update the ELO ratings that initially started off with a rating of 1000.
I tinkered with using pass by reference but not exactly sure how I should implement it as 2 different functions call the same rating variable.
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
const int K = 20; //constant used in http://clubelo.com/Ranking
//tokenize and extract the number of goals only
vector <string> tokenize(string s){
vector <string> tokens;
stringstream check1(s);
string intermediate;
// Tokenizing w.r.t. space ' '
while(getline(check1, intermediate, ' ')){
tokens.push_back(intermediate);
}
return tokens;
}
//calculating goal difference to calculate ELO rating
int GoalDifference (int goalsA, int goalsB){
int GoalDiff = abs(goalsA - goalsB);
int G;
if (GoalDiff == 0 || GoalDiff == 1)
G = 1;
else if (GoalDiff == 2)
G = 3/2;
else
G = (11+GoalDiff)/8;
return G;
}
//determine the result of the match by looking at goals
int result (int goalsA,int goalsB){
int result;
if (goalsA == goalsB)
result = 0.5;
else if (goalsA>goalsB)
result = 1;
else
result = 0;
return result;
}
// Function to calculate the Probability
float Probability(int rating1,int rating2){
return 1.0 / (1.0 *pow(10, 1.0 * ((rating1 - rating2)) / 400)+1);
}
//calculating new ELO rating
int ELOratings (int rating, int goalsa, int goalsb, int probability){
int deltapoints = K* GoalDifference(goalsa, goalsb) * (result(goalsa, goalsb) - probability);
return rating + deltapoints;
}
int main(){
int Ratinga = 1000, Ratingb = 1000;
int goalsA, goalsB, probA, probB, ELOp1, ELOp2;
ifstream inputFile;
string input;
inputFile.open("Scores of P1 vs P2.txt");
vector <string> ScoreTokens;
while (!inputFile.eof()) {
getline(inputFile,input);
ScoreTokens = tokenize(input);
goalsA = stoi(ScoreTokens[1]);
goalsB = stoi(ScoreTokens[3]);
probA = Probability(Ratinga, Ratingb);
probB = Probability(Ratingb, Ratinga);
ELOp1 = ELOratings(Ratinga, goalsA, goalsB, probA);
ELOp2 = ELOratings(Ratingb, goalsB, goalsA, probB);
cout << "The new rating for P1 is: " << ELOp1 << endl;
cout << "The new rating for P2 is: " << ELOp2 << endl << endl;
}
return 0;
}
Here are the scores and how I extracted the data:
P1 VS P2
Liverpool 2 United 2
Barca 2 Real 3
After calculations, after the first game, each should have a rating of 990. After the second game, P1 should be 970 and P2 should be 990.
But the actual output is 1000 after the first game.
After 2nd game:
P1: 1000
P2: 1020
The problem is that you are using integers everywhere for calculations that involve fractional numbers. For instance 3/2 is equal to 1, (not 1.5) because it's integer division and so the result is an integer.
Here's that function fixed
//calculating goal difference to calculate ELO rating
double GoalDifference (int goalsA, int goalsB){
int GoalDiff = abs(goalsA - goalsB);
double G;
if (GoalDiff == 0 || GoalDiff == 1)
G = 1.0;
else if (GoalDiff == 2)
G = 1.5;
else
G = (11+GoalDiff)/8.0;
return G;
}
Note the return type has been changed to double as well, because the result is a fractional quantity. But the goalsA and goalsB has been left as integers because they really are integers.
Basically you need to go through your code and at each point ask yourself whether the number is an integer or a fraction and change appropriately.
BTW, both float and double can be used for fractions, but in general you should prefer double as it's more precise and no less efficient.

cos(nx) in p/q form using Memoization

I want to calculate cos(nx) = p/q Using recursion and memoization so i tried Chebyshev Method for Recursive Method it works for small inputs of n but i want to do it for larger inputs like 10^18 etc. How should i approach it to calculate cos(nx) in p/q Form?
For larger Values of n i am getting Memory Problem How do i fix that?
cos(x) = a/b Known
#include <bits/stdc++.h>
using namespace std;
map<long, long> numerator;
map<long, long> denominator;
#define MODULO 1000000007
long a, b, n;
int main() {
cin >> a >> b;
cin >> n;
numerator[0] = 1;
numerator[1] = a;
denominator[0] = 1;
denominator[1] = b;
for (long i = 2; i <= n; ++i) {
numerator[i] = (long) (2 * a * numerator[i - 1] - b*numerator[i - 2]) % MODULO;
denominator[i] = (denominator[i - 1] * denominator[i - 2]) % MODULO;
}
cout << "numerator of cos(nx) = " << numerator[n] << " denominator = " << denominator[n] << endl;
}
lol Thats a contests question you're asking for. Shame on you. That's Codechef's February Challenge's Question. How low can you fall for some rating. smh

Can anyone Simplify this program related to calculating train fare?

Take the input of kilometers, and the class of journey(1, 2 or 3 for first, second and third class respectively), for a train journey. The program should then calculate the fare of the journey based on the following criteria:
I Could not do the program in one single equation, so I did it using if else statements. Can this program be made shorter and can the logic be designed without the need of the if else statements? Can the logic of the program be represented as a single mathematical equation(using only arithmetic operators)?
My Code:
//
// main.cpp
// c++
//
// Created by Aniansh Raj on 14/08/16.
// Copyright © 2016 Aniansh Raj. All rights reserved.
//
#include <iostream>
using namespace std;
int main()
{
unsigned int km, cl, amt;float r1, r2, r3;
cout<<"Enter distance in kilometer\n";
cin>>km;
cout<<"Enter Class(1, 2 or 3)\n";
cin>>cl;
switch(cl)
{
case 1:
r1=3;r2=2.5;r3=2;break;
case 2:
r1=2;r2=1.5;r3=1;break;
case 3:
r1=1.5;r2=1;r3=0.5;break;
default:
cout<<"Error!\n";
return 0;
}
if(km>=100&&km<=250)
amt=(100*r1)+(km-100)*r2;
else if(km>250)
amt=(100*r1)+(150*r2)+(amt-250)*r3;
else
amt=km*r1;
cout<<endl<<amt;
}
You can reorganize your code in many ways, but I don't think you could obtain exactly what you want.
For example you can store the prices in an array:
unsigned int price[3][3] = {
{300, 250, 200}, // first class, Rupee cents per km
{200, 150, 100}, // second class
{150, 100, 50}, // third class
};
Ask for the distance and the class, then calculate and print the amuont like this:
unsigned int amount;
if ( d <= 100 )
amount = d * price[c][0]; // c = cl - 1; considering your code
else if ( d <= 250 )
amount = 100 * price[c][0] + (d - 100) * price[c][1];
else
amount = 100 * price[c][0] + 150 * price[c][1] + (d - 250) * price[c][2];
std::cout << "distance: " << d << " price: " << amount / 100.0 << '\n';
Now, we can simplify those (linear) equations noticing that are of the form:
amount = constant + d * price
And precalculate the first part, which happens to be the same for all classes and depends only on the range. So, given this array:
unsigned int p0[] = {0, 5000, 17500};
The previous snippet can be rewritten (and "simplified") like this:
unsigned int index = d < 250 ? ( d < 100 ? 0 : 1 ) : 2;
unsigned int amount = p0[index] + d * price[cl - 1][index];
std::cout << "distance: " << d << " price: " << amount / 100.0 << '\n';
One other option, which only hides the conditional part inside a library function, can be:
unsigned int amount = std::min({
p0[0] + d * price[cl - 1][0],
p0[1] + d * price[cl - 1][1],
p0[2] + d * price[cl - 1][2]
});
std::cout << "distance: " << d << " price: " << amount / 100.0 << '\n';
Strictly speaking there's an equivalent ternary statement of
if(km>=100&&km<=250)
amt=(100*r1)+(km-100)*r2;
else if(km>250)
amt=(100*r1)+(150*r2)+(amt-250)*r3;
else
amt=km*r1;
in the form of
amt = (km>=100&&km<=250) ? (100*r1)+(km-100)*r2 : (km>250) ? (100*r1)+(150*r2)+(amt-250)*r3 : km*r1;
Which isn't really as readable as the prior block. If what you're looking for is to have it in a formula, then this should be a bit cleaner than the above:
amt = km * r1 +
( km > 100 ?
km > 250 ?
150 * r2 + (km - 250) * r3 - (km - 100) * r1 :
(km - 100) * (r2 - r1) :
0 ); /* readblity */
Although I don't understand why if statements are bad. It's more readable and has the same performance.

Multiplying integers the long way

I'm trying to create long int multiplication function. In math for multiplying 2 numbers for example 123 X 456, I do:
(12 * 10^1 + 3)( 45 * 10^1 + 6) =
(540 * 10^2) + (72 * 10^1) + (135 * 10^1) + 18 = 15129
I created a small program for this algorithm but it didn't work right.
I don't know where my problem is. Can you help me to understand and correct that?
Tnx
int digits(int n) {
int digit = 0;
while (n>0){
n/=10;
digit++;
}
return digit;
}
long int longMult(long int a, long int b) {
long int x,y,w,z;
int digitA = digits(a);
int digitB = digits(b);
if((a==0) || (b==0)) {
return 0;
} else if (digitA < 2 || digitB < 2) {
return a*b;
} else {
int powA = digitA / 2;
int powB = digitB / 2;
//for first number
x = a/(10^powA);
y = a%(10^powA);
//for second number
w = b/(10^powB);
z = b%(10^powB);
return ( longMult(x,w)*(10^(powA*powB)) + longMult(x,z) +
longMult(w,y)*(10^(powA*powB)) + longMult(y,z));
}
}
int main()
{
cout << digits(23) << endl; // for test
cout << longMult(24,24); // must be 576 but output is 96
return 0;
}
The expression
10^powA
does a bitwise exclusive or, and doesn't raise 10 to the power of powA, as you appear to expect.
You may want to define something like
long powli(int b, long e) {return e?b*powli(b,e-1):1;}
Then instead you can use
powli(10,powA)
Edit: There is also a problem with the way the values are combined:
return ( longMult(x,w)*(10^(powA*powB)) + longMult(x,z) +
longMult(w,y)*(10^(powA*powB)) + longMult(y,z));
Look into the maths, because multiplying the exponents makes little sense.
Also the combinations of adjustments to values is wrong, eg (10*a + b)(10*c + d) = 10*10*a*c + 10*a*d + 10*b*d +b*d. So check on your algebra.