I ran this codes only my zybook class, it gives me the wrong answers and tells me to use floating numbers for the functions. How can I use floating point numbers for square function.
edit:
sorry for the confusion
#include <iostream>
#include <string>
using namespace std;
float squareRoot( float s) {
float xn;
if (s == 0) {
xn = 0;
}
else {
xn = s / 2.0;
int counter = 1;
while (counter <= 10) {
xn = (xn + (s/ xn)) / 2.0;
counter = counter + 1;
}
}
return xn;
} int square(int what) {
return what* what;
}
int main() {
float sideA, sideB, sideC;
string answer = "yes";
while (answer == "yes") {
cout <<" Enter side A: ";
cin >> sideA;
cout << sideA << endl;
cout <<" Enter side B: ";
cin >> sideB;
cout << sideB << endl;
sideC = squareRoot( square( sideA) + square( sideB));
cout <<"Side C is " << sideC << endl;
cout <<"Continue? ";
cin >> answer;
cout << answer << endl;
}
return 0;
}
Your function:
int square (int what){
return what * what;
}
should instead return a float. When you pass the floating point numbers to this function, it returns them as integers so instead of 3.3 and 4.4 getting squared, 3 and 4 do.
You should return a float and change what to a float as well.
Related
i am not sure how to resolve this math problem. what should i recall and where did i miss something. i have tried different opportunities. i think i just call not existing index or something like that..
#include <iostream>
using namespace std;
double recur(int n, int x);
double x;
int number;
int main()
{
cout << "enter n: " ;
cin >> number;
cout << endl;
do
{
cout << "enter float x!=0: ";
cin >> x;
cout << endl;
} while (x==0);
cout << "recur(" << number << "," << x << ")=" << recur(number, x) << endl;
system("pause");
}
double recur(int n, int x)
{
if (n > 1) return (x * recur(n, x - n) * recur(n - 1, x));
else if( n == 1) return x * recur(n,x) - x;
else return 1;
}
Formula:
For formula:
It's implementation:
#include <iostream>
#include<cmath>
using namespace std;
double recur(int n, int x);
double x;
int number;
int main()
{
cout << "enter n: " ;
cin >> number;
cout << endl;
do
{
cout << "enter float x!=0: ";
cin >> x;
cout << endl;
} while (x==0);
cout << "recur(" << number << "," << x << ")=" << recur(number, x) << endl;
system("pause");
}
double recur(int n, int x)
{
if (n > 1) return (x*(pow(log(x),n)) - n*(recur(n-1,x)));
else if( n == 1) return x * log(x) - x;
}
For n>1 line
(x*(pow(log(x),n)) = x*(ln x)^n
n*(recur(n-1,x)) = n* integral( (lnx)^(n-1) ) <- In next recursion call one power will get reduced
For n=1 line
x * log(x) - x = xlnx - x <- base condition(where recursive call will stop)
In this implementation recur(n,x) denotes integration of (lnx)^n w.r.t x.
Your integral isn't the same as the log portion, so you should probably split that out.
double ln_n(int n, double x) {
while (n --> 0) x = log(x);
return x;
}
double integral(int n, double x) {
if (n > 0) return (x * ln_n(n, x)) - (n * integral(n - 1, x));
return x;
}
See it live
A class I've been working on for a few days, running into an error I'm unsure how to fix.
#include <iostream> // for cin, cout, endl
#include <string>
#include <iomanip> // formatting floats
using namespace std;
void programHeader();
void footer();
void printEmployeeInfo(struct employeeInfo);
struct employeeInfo
{
int employeeID;
char employeeName[20];
double payRate;
int employeeType;
};
float findGrossPay(employeeInfo myEmployee, double , int);
void payrollDisplay(employeeInfo myEmployee, double, double, double, float, float);
//prototype declerations
int main()
{
// decleration of variables
float inputNumber1;
int num1;
int num2;
int num3;
int num4;
employeeInfo myEmployee[4];
float totalGross;
float totalNet;
int maxName = 20;
int location;
double hoursArray[4];
double grossPay[4];
double tax[4];
double netPay[4];
// input section
programHeader();
num4 = 0;
location = 0;
for (int c = 0; c < 4; c++) // fill in the array of structs
{
while (true); // validation loop
{
cout << "Employee ID: ";
cin >> num1;
if (num1 > 0);
{
myEmployee[c].employeeID = num1;
break;
} // end if
if (num1 <= 0)
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end else if
} // end while
cout << "Employee Name: ";
cin.getline(myEmployee[c].employeeName, maxName);
while (true); // validation loop
{
cout << "Pay rate: ";
cin >> num2;
if (num2 > 0);
{
myEmployee[c].payRate = num2;
break;
} // end if
if (num2 <= 0)
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end if
} // end while
while (true) // validation loop
{
cout << "Type: ";
cin >> num3;
if ((num3 == 1) || (num3 == 0))
{
myEmployee[c].employeeType = num3;
break;
} // end if
else
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end else
} // end while
} // end for(c)
for (int h = 0; h < 4; h++); // parallel array to hold hours worked
{
cout << "Hours worked for " << myEmployee[num4].employeeName << ": ";
cin >> hoursArray[num4];
num4 = num4 +1;
} // end for(h)
// calculation section
// displays the results
for (int l = 0; l < 4; l++) // l for location
{
grossPay[l] = findGrossPay(myEmployee[4], hoursArray[4], location);
location = location + 1;
} // end for(l)
for (int t = 0; t < 4; t++) // get taxes and net pay for each
{
tax[t] = grossPay[t] * (15 / 100);
netPay[t] = grossPay[t] - tax[t];
}
for (int i = 0; i < 4; i++)
{
totalGross = totalGross + grossPay[i];
totalNet = totalNet + netPay[i];
} // end of for
payrollDisplay(myEmployee[4], grossPay[4], tax[4], netPay[4], totalGross, totalNet);
footer();
system("PAUSE");
return 0;
}// end of main
float findGrossPay(employeeInfo myEmployee[4], double hoursArray[4], int l) // l stands for location
{
float numGrossPay;
if (myEmployee[l].employeeType == 1) // management
{
numGrossPay = myEmployee[l].payRate * hoursArray[l];
} // end if
else if (myEmployee[l].employeeType == 0) // union members
{
if (hoursArray[l] > 40)
{
numGrossPay = myEmployee[l].payRate * 40 + (hoursArray[l] - 40) * (myEmployee[l].payRate * 1.5);
} // end if
else
{
numGrossPay = myEmployee[l].payRate * hoursArray[l];
} // end else
} // end else if
return numGrossPay;
}
void payrollDisplay(employeeInfo myEmployee[4], double grossPay[4], double tax[4], double netPay[4], float totalGross, float totalNet)
{
cout << "------------------------------------------------------------" << endl;
cout << "\nPayroll Report\n" << endl;
cout << "ID \tName" << "\t\tGross Pay \tTax \tNet Pay" << endl;
for (int i = 0; i < 4; i++) // to print each employee
{
cout << myEmployee[i].employeeID << "\t" << myEmployee[i].employeeName << "\t\t" << grossPay[i]
<< "\t" << tax[i] << "\t" << netPay[i] << endl;
} // for(i)
cout << "\nTotal Gross Pay \t$" << totalGross << endl;
cout << "Total Net Pay \t$" << totalNet << endl;
}
It's giving me an error stating there is an undefined reference to these lines in main():
grossPay[l] = findGrossPay(myEmployee[4], hoursArray[4], location);
and
payrollDisplay(myEmployee[4], grossPay[4], tax[4], netPay[4], totalGross, totalNet);
The "undefined reference" errors are because your function declarations do not match their definitions.
You have declared findGrossPay() and payrollDisplay() as taking in a single employeeInfo and related values for that one employee, but then your definitions are taking in arrays of employees and values:
//declaration
float findGrossPay(employeeInfo myEmployee, double , int);
//definition
float findGrossPay(employeeInfo myEmployee[4], double hoursArray[4], int l)
// declaration
void payrollDisplay(employeeInfo myEmployee, double, double, double, float, float);
//definition
void payrollDisplay(employeeInfo myEmployee[4], double grossPay[4], double tax[4], double netPay[4], float totalGross, float totalNet)
As such, the linker can't find matching definitions for the functions you are actually calling.
And, to make that worse, the places where you are calling these functions are accessing array elements out of bounds, which is undefined behavior.
After you fix that problem, you should then get "undefined reference" errors for programHeader() and footer(), since their definitions are missing completely.
After fixing that, there are still other problems with your code:
you have a number of if and for/while loops that have an erroneous ; on them
you are accessing arrays incorrectly in some places
you have uninitialized variables in some of your calculations
With that said, try something more like this:
#include <iostream> // for cin, cout, endl
#include <string>
#include <iomanip> // formatting floats
#include <limits>
using namespace std;
struct employeeInfo
{
int employeeID;
string employeeName;
double payRate;
int employeeType;
};
//prototype declerations
void programHeader();
void footer();
int promptForNumber(const string &prompt, int minValue = 0, int maxValue = numeric_limits<int>::max());
string promptForString(const string &prompt);
float findGrossPay(const employeeInfo &myEmployee, double hours);
void payrollDisplay(const employeeInfo myEmployee[4], const double grossPay[4], const double tax[4], const double netPay[4]);
int main()
{
// decleration of variables
employeeInfo myEmployee[4];
double hours[4];
double grossPay[4];
double tax[4];
double netPay[4];
int num;
// input section
programHeader();
for (int c = 0; c < 4; c++) // fill in the array of structs
{
myEmployee[c].employeeID = promptForNumber("Employee ID", 1);
myEmployee[c].employeeName = promptForString("Employee Name");
myEmployee[c].payRate = promptForNumber("Pay rate", 1);
myEmployee[c].employeeType = promptForNumber("Type", 0, 1);
}
for (int h = 0; h < 4; h++) // parallel array to hold hours worked
{
hours[h] = promptForNumber("Hours worked for " << myEmployee[h].employeeName);
}
// calculation section
for (int l = 0; l < 4; l++) // l for location
{
grossPay[l] = findGrossPay(myEmployee[l], hours[l]);
}
for (int t = 0; t < 4; t++) // get taxes and net pay for each
{
tax[t] = grossPay[t] * (15 / 100);
netPay[t] = grossPay[t] - tax[t];
}
// displays the results
payrollDisplay(myEmployee, grossPay, tax, netPay);
footer();
system("PAUSE");
return 0;
}
void programHeader()
{
// print out something here...
}
void footer()
{
// print out something here...
}
int promptForNumber(const string &prompt, int minValue, int maxValue)
{
int num;
while (true) // validation loop
{
cout << prompt << ": ";
if (cin >> num)
{
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if ((num >= minValue && num <= maxValue)
break;
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "\nERROR PLEASE TRY AGAIN" << endl;
}
return num;
}
string promptForString(const string &prompt)
{
string input;
while (true) // validation loop
{
cout << prompt << ": ";
if (getline(cin, input) && !input.empty())
break;
cout << "\nERROR PLEASE TRY AGAIN" << endl;
}
return input;
}
float findGrossPay(const employeeInfo &myEmployee, double hours)
{
if (myEmployee.employeeType == 1) // management
{
return myEmployee.payRate * hours;
}
// must be myEmployee.employeeType == 0 // union members
if (hours > 40)
{
return myEmployee.payRate * 40 + (hours - 40) * (myEmployee.payRate * 1.5);
}
else
{
return myEmployee.payRate * hours;
}
}
void payrollDisplay(const employeeInfo myEmployee[4], const double grossPay[4], const double tax[4], const double netPay[4])
{
float totalGross = 0.0f;
float totalNet = 0.0f;
cout << "------------------------------------------------------------" << endl;
cout << "\nPayroll Report\n" << endl;
cout << "ID \tName" << "\t\tGross Pay \tTax \tNet Pay" << endl;
for (int i = 0; i < 4; i++) // to print each employee
{
cout << myEmployee[i].employeeID << "\t" << myEmployee[i].employeeName << "\t\t" << grossPay[i] << "\t" << tax[i] << "\t" << netPay[i] << endl;
totalGross += grossPay[i];
totalNet += netPay[i];
}
cout << "\nTotal Gross Pay \t$" << totalGross << endl;
cout << "Total Net Pay \t$" << totalNet << endl;
}
That said, you might consider moving the hours/grossPay/tax/netPay values into the employeeInfo struct, so that you have to manage only 1 array and not 5 parallel arrays.
I'm trying to print the output of the function after my values are sent to the function. The cout statement needs a string but I'm not sure how I can return a string from my reduce_fraction function while keeping the math correct. In my add_fraction function, you'll see that I simply want to print the added fraction then the reduced fraction right below it. The compiler returns no errors but the output just shows the "Improper Fraction" answer.
#include <iostream>
#include <string>
using namespace std;
void reduce_fraction (int top, int bottom)
{
for (int i = top * bottom; i > 1; i--) {
if ((top % i == 0) && (bottom % i == 0)) {
bottom /= i;
top /= i;
}
}
}
void add_fraction (int numerator, int numerator2, int denominator, int
denominator2)
{
int top;
int bottom;
top = numerator2 * denominator + denominator2 * numerator;
bottom = denominator2 * denominator;
cout << "Improper Fraction -> ";
cout << top << "/" << bottom << endl;
cout << "Simplified Fraction -> ";
reduce_fraction(top, bottom);
}
int main()
{
int numerator;
int denominator;
int numerator2;
int denominator2;
char operation;
cout << "Input the numerator: ";
cin >> numerator;
cout << "Input the denominator: ";
cin >> denominator;
cout << "Input the numerator2: ";
cin >> numerator2;
cout << "Input the denominator: ";
cin >> denominator2;
cout << "Input the operation: ";
cin >> operation;
if (operation == '+'){
add_fraction(numerator, numerator2, denominator, denominator2);
}
return 0;
}
Use reference to reflect the changes in top and bottom
and print those in your add_fraction function after calling reduce_fraction
void reduce_fraction ( int & top, int & bottom)
{ ~~~ ~~~
//...
}
Then,
reduce_fraction(top, bottom);
cout << top << "/" << bottom << endl;
When compiling the following code under Xcode 4.5 (Mac), compilation fails with the following error message:
call to 'pow' is ambiguous
Why? Thanks!
#include <iostream>
#include <cmath>
#include <limits>
using namespace std;
int main()
{
cout << "\tSquare root calculator using an emulation the ENIAC's algorithm." << endl
<< endl;
long long m;
while ((cout << "Enter a positive integer:" << endl)
&& (!(cin >> m) || m < 0 || m > 9999999999)) //10-digit maxium
{
cout << "Out of range.";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
again:
long long l = m;
//Find out how big the integer is and adjust k accordingly.
int order = -1;
long long temp = m;
do
{
temp /= 10;
order++;
} while (temp/10);
int k = order/2;
//Step 1
long long a = -1;
do
{
a+=2;
m -= a*pow(100,k);
} while (m >= 0);
while (k > 0)
{
k--;
//Step 2
if (m < 0)
{
a = 10*a+9;
for (;m < 0;a -= 2)
{
m += a*pow(100,k);
}
a += 2;
}
//Step 3
else
{
a = 10*a-9;
for(;m >= 0;a += 2)
{
m -= a*pow(100,k);
}
a -= 2;
}
}
//Step 4
cout << endl << "The square root of " << l << " is greater than or equal to "
<< (a-1)/2 << " and less than " << (a+1)/2 << "." << endl << endl;
while ((cout << "Enter a positive integer to calculate again, or zero to exit." << endl)
&& (!(cin >> m) || m < 0 || m > 9999999999))
{
cout << "Out of range.";
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if (m > 0) goto again;
return 0;
}
As you can see here there is no pow(int,int);
pow
<cmath>
double pow ( double base, double exponent );
long double pow ( long double base, long double exponent );
float pow ( float base, float exponent );
double pow ( double base, int exponent );
long double pow ( long double base, int exponent );
This link looks like it answers your question:
http://bytes.com/topic/c/answers/727736-ambiguous-call-pow
It looks like the pow() function doesn't like integers.
I am currently doing a task in a book which asks me to calculate the mathematical constant e using the while loop. I managed that fairly easily, however I am having troubles calculating e^x, whereas the user inputs x and the degree of accuracy. The code I used for computing e is:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
while (x <= degreeOfAccuracy)
{
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
e += (1/number);
x++;
}
cout << endl << "The mathematical constantr e is: "
<< setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
However, when I tried e^x the following code returned a completely wrong value:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int degreeOfAccuracy, x = 1, exponent;
long double e = 1;
cout << "Enter degree of accuracy of mathimatical constant e: ";
cin >> degreeOfAccuracy;
cout << "Enter the number of which you wish to raise to e: ";
cin >> exponent;
int temp = exponent;
while (x <= degreeOfAccuracy)
{
exponent = temp;
int conter = x;
int intial = x;
long double number = x;
int counter = 1;
while (conter > 1)
{
number = number*(intial-counter);
counter++;
conter--;
}
int counterr = 1;
while (counterr < x)
{
exponent *= exponent;
counterr++;
}
e += (exponent/number);
x++;
}
cout << endl << "The mathematical constantr e is: " << setprecision(degreeOfAccuracy) << fixed << e << endl;
system("pause");
return 0;
}
Any ideas where the calculations went wrong?
This line:
exponent *= exponent;
is wrong. It should be:
exponent *= temp;