Why doesn't this simple C++ work? - c++

I need to write a program that calculates the cost for the distance traveled following these rules
Each of the first 100 miles (inclusive) cost £5.50
Over 100 miles and up to 500 miles (inclusive): £4.00 per mile.
Over 500 miles: £2.50 per mile.
This is my program so far
#include <iostream> //for cin >> and cout <<
using namespace std;
int main() // main algorithm
{
double distance;
double Milecost1;
double Milecost2;
double Milecost3;
double totalcost;
cout << "enter distance";
cin >> (distance);
void CFM();
if (distance >= 100) {
Milecost1 = 100 * 5.50;
} else {
totalcost = distance * 5.50;
}
void CSM();
if ( (distance >100) && (distance <= 500) ) {
Milecost2 = (distance - 100) *4.00;
}
void CTM();
if (distance > 500) {
Milecost3 = distance - 500 * 2.50;
}
void totalcost1();
totalcost = Milecost1 + Milecost2 + Milecost3;
cout << "the total cost for the distance travelled is" << totalcost
system("pause"); //to hold the output screen
return(0);
}
My first question is, is the maths correct to work out the cost?
Second question is I run the program and it says Milecost 2 is being used without being initialized how do I solve this?

No, the math is not correct, e.g. with distance = 501, you'd get
Milecost1: 550
Milecost2: (unitialised)
Milecost3: 2.50
That's assuming you correct the operator precedence on Milecost3, since right now you're multiplying 500 times 2.5 and subtracting that from distance.
Milecost2 is only assigned when distance is within its relevant values, instead, it should be 0 for distance <= 100 AND it should also be calculated when distance > 500, if I understood the exercise correctly.

I would write it down as:
#include <iostream> //for cin >> and cout <<
using namespace std;
int main() // main algorithm
{
double distance;
double Milecost1;
double Milecost2;
double Milecost3;
double totalcost;
cout << "enter distance";
cin >> (distance);
if (distance >= 100) {
Milecost1 = 100 * 5.50;
} else {
Milecost1 = distance * 5.50;
}
if ( (distance >100) && (distance <= 500) ) {
Milecost2 = (distance - 100) *4.00;
} else {
Milecost2 = 0;
}
if (distance > 500) {
Milecost3 = distance - 500 * 2.50;
} else {
Milecost3 = 0;
}
totalcost = Milecost1 + Milecost2 + Milecost3;
cout << "the total cost for the distance travelled is" << totalcost ;
system("pause"); //to hold the output screen
return(0);
}
getting rid of your calls to undefined functions; and not depending on initialization of variables to 0.

I think this should work fine
void main(void)
{
double distance;
double cost;
if(distance <= 100)
{
cost = distance * 5.50;
}
else if(distance > 100 && distance <= 500)
{
cost = 100 * 5.50;
cost += 4.00 * (distance - 100);
}
else
{
int temp = 100;
cost = temp * 5,50;
temp = 400;
cost += temp * 4.00;
temp = distance - 500;
cost += temp * 2.50;
}
}

Personally, this is the way I'd do it:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
double distance;
cout << "Enter distance (Miles): ";
cin >> distance;
double milesOver500 = max(0.0, distance-500.0);
double milesInBetween = max(0.0, distance-milesOver500-100.0);
double milesUnder100 = max(0.0, distance-milesInBetween-milesOver500);
double totalCost = milesOver500 * 2.5 +
milesInBetween * 4.0 +
milesUnder100 * 5.5;
cout << "The total cost for the distance traveled is £" << totalCost << endl;
return 0;
}
In your implementation, Milecost2 is only initialized if the conditional (distance >100) && (distance <= 500) is true, which won't always be the case. In the code above, everything is initialized at the time of its declaration with a meaningful value that doesn't need to be computed later. It just so happens that this approach works well in this case, but there are others where it's a bit more difficult to do so. When such cases arise you should try to assign some meaningful default value to each variable you declare at the time of its declaration which can change if certain conditions arise.

Related

C++ Newton Raphson method is slower than bisection?

My task is to find the root of a function with both the Newton Raphson and the bisection method within an error margin of 10E-7.
The point of all that is, that we learn that the Newton Raphson method is faster and more effective.
Now for some reason I come to the opposite result. Although I am aware that the initial guess of the root in both methods strongly affects the number of necessary iterations. But I entered a similar guess in both algorithms and my fellow students dont get the result I do.
Bisection method:
#include <iostream>
#include <iomanip>
using namespace std;
//Declaring the given function
double func1(double x) {
return 0.00000000027 * (x - 10000000) - 0.16460351745 * (-1 + ((1000000000) / (x))) * 1 / (sqrt(x));
}
int main() {
std::fixed;
//Initial guess: root ist at 10 to the 7.
double x1 = 10000000;
double x2 = 1000000000;
double eps = 0.0000001;
int i = 0;
double x0[100000];
x0[0] =0;
//Exception handler
if (func1(x1) * func1(x2) > 0) {
cout << "Root is not inside the bracket.";
goto end;
}
goto start;
//Bisection Algorithm
while (abs(x0[i] - x0[i-1]) >= eps) {
start:
i = i + 1;
x0[i] = 0.5 * (x1 + x2);
if (func1(x1) * func1(x0[i]) < 0) {
x2 = x0[i];
}
else {
x1 = x0[i];
}
}
cout << endl << "Bisection Method: " << fixed << setprecision(10) << x0[i] << endl << "Iterations: " << i << endl << endl << endl << endl << endl;
end:
return 0;
}
}
Newton Raphson:
#include <iostream>
#include <iomanip>
using namespace std;
// Declaring the function and its derivative
double func1(double x) {
return 0.00000000027 * (x - 10000000) - 0.16460351745 * (-1 + ((1000000000) / (x))) * 1 / (sqrt(x));
}
double funcderiv1(double x) {
return 0.00000000027+((0.1646035174)/(2*x*x*sqrt(x)))*(30000000-x);
}
int main()
{
std::fixed;
double eps = 1;
double x_start = 10000000;
double c;
int i = 0;
while (eps >= 0.0000001) {
c = x_start - ((func1(x_start)) / (funcderiv1(x_start)));
eps = abs(func1(x_start) / funcderiv1(x_start));
x_start = c;
i = i + 1;
}
cout << fixed << setprecision(5) << "RESULT " << c << endl << " Iterations: " << i << endl;
}
The root is at 17903534.23630
Does anyone know why my bisection method needs 55 iterations while Newton Raphson takes like 82?
For the function
f(x) = A * (x - B) - C * (D / x - 1) / sqrt(x)
A = 0.00000000027
B = 10000000
C = 0.16460351745
D = 1000000000
the correct derivative is:
f'(x) = A - C (x - 3D) / (2 * x * x * sqrt(x))
Compare this with your expression:
g(x) = A - C (x - 3B) / (2 * x * x * sqrt(x))
After fixing the formula (by adding two zeros), your code makes 6 iterations:
RESULT 17903534.23630
Iterations: 6

brute-force search program with C++

I am new to C++. Recently I was going through the tutorial from google developer: https://developers.google.com/edu/c++/getting-started
Here is this simple match puzzle with brute force search for solution:
Horses cost $10, pigs cost $3, and rabbits are only $0.50. A farmer buys 100 animals for $100, How many of each animal did he buy?
Here is my code:
#include <iostream>
using namespace std;
int main() {
int pHorse = 10;
int pPig = 3;
int pRabbit = 0.5;
for (int i = 0; i <= 100 / pHorse; ++i) {
for (int j = 0; j <= ((100 - i * pHorse) / pPig); ++j) {
int money = (100 - pHorse * i - pPig * j);
if (pRabbit * (100 - i - j) == money) {
cout << "The number of Horses are: " << i << endl;
cout << "The number of Pigs are: " << j << endl;
cout << "The number of Rabbits are: " << 100 - i - j << endl;
}
}
}
return 0;
}
However, it is giving me ridiculous answers like [10 0 90], which was not correct obviously.
I could not figure out where is the problem. Any idea? Thanks in advance.
Instead of
int pRabbit = 0.5;
try
double pRabbit = 0.5;
An int won't hold 0.5. Try a float instead.
0.5 is not an integer number. It is a floating point number so you can not store 0.5 in an integer variable. you can use a double or float variable.
Like this:
double pRabbit = 0.5;
or
float pRabbit = 0.5;

What is the appropriate loop for this amortization formula?

I am trying to print out the variable *loan_Amt* when the monthly payment exceeds/is equal to the 30% amount that is found in the *monthly_payment* function. This is my first attempt at writing a c++ program with functions!
#include<iostream>
#include<conio.h>
#include<string>
#include<iomanip>
#include<math.h>
using namespace std;
double monthly_Payment (double amt_Amt)
{
double r;
r = ( amt_Amt/ 12) * 30/100;
return (r);
}
double interest_Calculate(double interest_Amt)
{
double r;
r = (interest_Amt * .010);
return (r);
}
//double loan_Calculate()
//{
//int x = interest_Calculate(interest_Rate);
//double monthly = (loan_Amt * x) / (1 - pow(1.0 + i,-(12*30)));
//for (((int loan_Amt = 20000) * (x/12)) / pow(1.0 + i,-(12*30)); loan_Amt>0; loan_Amt++);
//}
int main()
{
double gross_Salary;
double interest_Rate;
int x;
int i;
double monthly;
std::cout << "Please enter your yearly gross salary:";
std::cin >> gross_Salary;
std::cout << "Please enter an interest rate:";
std::cin >> interest_Rate;
int z;
z = monthly_Payment (gross_Salary);
std::cout << "The target (30 percent of monthly salary) monthly payment range is:" << z;
for ( int loan_Amt = 0; loan_Amt <= 5000000; x++ ) {
do {
x = interest_Calculate(interest_Rate);
monthly = (loan_Amt * x) / (1 - pow(1.0 + x,-(12*30)));
std::cout << loan_Amt;
} while (monthly >= z );
}
getch();
return 0;
}
The for loop has problem, I think,
for ( int loan_Amt = 0; loan_Amt <= 5000000; x++ ) {
do {
x = interest_Calculate(interest_Rate);
monthly = (loan_Amt * x) / (1 - pow(1.0 + x,-(12*30)));
std::cout << loan_Amt;
} while (monthly >= z );
}
loan_Amt will never change its value, so this is an infinite loop.
This line in the do-while loop,
std::cout << loan_Amt;
will always print zero

must be modifiable value error?

below is a .cpp file that i am including in another .cpp file. I am getting an error that states emp.grosPay() must be a modifiable lvalue. any ideas on fixing it?
#include <iostream>
#include <string>
#include "weeklyEmp.h"
using namespace std;
const double WEEKLY_ALLOWANCE = 39.42;
const double FICA_TAX_RATE = 0.0765;
weeklyEmp::weeklyEmp()
{
my_name = ?name?;
}
weeklyEmp::weeklyEmp(string initName,
double initHours,
double initRate,
int initExemptions,
string initFilingStatus)
{
my_name; initName;
my_hours; initHours;
my_rate; initRate;
my_exemptions; initExemptions;
my_filingStatus; initFilingStatus;
}
//--modifiers
void weeklyEmp::set_hours(double thisWeeksHours)
//post: Set the hours worked for a given week
{
my_hours = thisWeeksHours;
}
void weeklyEmp::set_rate(double thisWeeksRate)
//post: Change the employee's hourly rate of pay
{
my_rate = thisWeeksRate;
}
//--accessors
double weeklyEmp::grosPay() const
//post: Return gross pay with overtime
{if(my_hours <=40) return my_hours * my_rate;
else
return (40*my_rate) + (my_hours-40) * 1.5 * my_rate;
}
double weeklyEmp::incomeTax() const
//post: Return the federal income tax
{
double result(0.0);
double taxableIncome(grosPay() - my_exemptions * WEEKLY_ALLOWANCE);
if(my_filingStatus == "S" || my_filingStatus == "s")
{
if (taxableIncome <= 23.00)
result = 0.00;
else if(taxableIncome <= 397.00)
result = 0.15 * (taxableIncome - 23.00);
else if(taxableIncome <= 928.00)
result = 56.10 + 0.28 * (taxableIncome - 397.00);
else if(taxableIncome <= 2121.00)
result = 204.78 + 0.33 * (taxableIncome - 928.00);
else
result = 598.47 + 0.28 * (taxableIncome - 2121.00);
}
if(my_filingStatus == "M" || my_filingStatus == "m")
{
if(taxableIncome <= 65.00)
result = 0.00;
else if(taxableIncome <= 689.00)
result = 0.15 * (taxableIncome - 65.00);
else if(taxableIncome <= 1573.00)
result = 93.60 + 0.28 * (taxableIncome - 689.00);
else if(taxableIncome <= 3858.00)
result = 341.12 + 0.33 * (taxableIncome - 1573.00);
else
result = 1095.17 + 0.28 * (taxableIncome - 3858.00);
}
/* round to the nearest penny */
/* include compfun.cpp for round function */
result =(result, 2);
return result;
}
double weeklyEmp::FICATax() const
//post: Return the social security tax
{
return grosPay() * FICA_TAX_RATE;
}
string weeklyEmp::name() const
//post: Return the employee's name
{ return my_name;
}
The portion of code with the error is below and marked * **
int main()
{
string name;
double rate;
double hours;
int exemptions;
string filingStatus;
cout <<"Name: ";
cin >> name;
cout << "Hourly Rate:";
cin >> rate;
cout << "Hours Worked:";
cin >> hours;
cout << "Exemptions: ";
cin >> exemptions;
cout<< "S) ingle / M) arried: ";
cin >> filingStatus;
cout << " " << endl;
weeklyEmp emp(name, hours, rate, exemptions, filingStatus);
double net = ***emp.grosPay()*** = emp.incomeTax() - emp.FICATax();
}
double net = emp.grosPay() = emp.incomeTax() - emp.FICATax();
// ^^^
grosPay doesn't return a reference, so I'm assuming you didn't mean to use an = sign there. May have been a slip of the thumb.
Did you mean to use the minus operator -?:
double net = emp.grosPay() - emp.incomeTax() - emp.FICATax();
// ^^^
The error was occurring because you can't modify a const object, an object returned by a const function, or an rvalue that isn't bound to a non-const rvalue-reference.
double net = ***emp.grosPay()*** = emp.incomeTax() - emp.FICATax();
^^^
The second '=' should be a '-' sign; I think you're trying to subtract, not assign.

Vastly different output C++ monte carlo approximation

doing a C++ approximation of Pi using a random number generator, output works exactly as expected on my AMD 64 machine running Ubuntu, however on my school machine the second algorithm I've implemented is broken, and would love some insight as to why. Code is as follows:
#ifndef RANDOMNUMBER_H_
#define RANDOMNUMBER_H_
class RandomNumber {
public:
RandomNumber() {
x = time(NULL);
m = pow(2, 19); //some constant value
M = 65915 * 7915; //multiply of some simple numbers p and q
method = 1;
}
RandomNumber(int seed) {
x = ((seed > 0) ? seed : time(NULL));
m = pow(2, 19); //some constant value
method = 1; //method number
M = 6543 * 7915; //multiply of some simple numbers p and q
}
void setSeed(long int seed) {
x = seed; //set start value
}
void chooseMethod(int method) {
this->method = ((method > 0 && method <= 2) ? method : 1); //choose one of two method
}
long int linearCongruential() { //first generator, that uses linear congruential method
long int c = 0; // some constant
long int a = 69069; //some constant
x = (a * x + c) % m; //solution next value
return x;
}
long int BBS() { //algorithm Blum - Blum - Shub
x = (long int) (pow(x, 2)) % M;
return x;
}
double nextPoint() { //return random number in range (-1;1)
double point;
if (method == 1) //use first method
point = linearCongruential() / double(m);
else
point = BBS() / double(M);
return point;
}
private:
long int x; //current value
long int m; // some range for first method
long int M; //some range for second method
int method; //method number
};
#endif /* RANDOMNUMBER_H_ */
and test class:
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <iomanip>
#include "RandomNumber.h"
using namespace std;
int main(int argc, char* argv[]) {
cout.setf(ios::fixed);
cout.precision(6);
RandomNumber random;
random.setSeed(argc);
srand((unsigned) time(NULL));
cout << "---------------------------------" << endl;
cout << " Monte Carlo Pi Approximation" << endl;
cout << "---------------------------------" << endl;
cout << " Enter number of points: ";
long int k1;
cin >> k1;
cout << "Select generator number: ";
int method;
cin >> method;
random.chooseMethod(method);
cout << "---------------------------------" << endl;
long int k2 = 0;
double sumX = 0;
double sumY = 0;
for (long int i = 0; i < k1; i++) {
double x = pow(-1, int(random.nextPoint() * 10) % 2)
* random.nextPoint();
double y = pow(-1, int(random.nextPoint() * 10) % 2)
* random.nextPoint();
sumX += x;
sumY += y;
if ((pow(x, 2) + pow(y, 2)) <= 1)
k2++;
}
double pi = 4 * (double(k2) / k1);
cout << "M(X) = " << setw(10) << sumX / k1 << endl; //mathematical expectation of x
cout << "M(Y) = " << setw(10) << sumY / k1 << endl; //mathematical expectation of y
cout << endl << "Pi = " << pi << endl << endl; //approximate Pi
return 0;
}
The second method returns 4.000 consistently on my lab machine, yet returns a rather close approximation on my personal machine.
For one thing, the BBS generator as you're using it will always return 1.
Since your program takes no arguments, presumably its argc will be 1. You pass argc as the seed (why?), so the initial value of x is 1.
BBS() has the following logic:
x = (long int) (pow(x, 2)) % M;
Clearly, 1 squared modulo M gives 1, so x never changes.
When you run the simulation with such a generator, your program will always output 4.
P.S. Wikipedia has the following to say about the initial value x0 for Blum Blum Shub:
The seed x0 should be an integer that's co-prime to M (i.e. p and q are not factors of x0) and not 1 or 0.