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
#include <iostream>
#include <math.h>
using namespace std;
int sum (int x);
int factorial (int y);
int greatest (int p, int q, int r);
int percentage (int m1, int m2, int m3, int m4, int m5);
int formula (int r, int h);
int voter_age (int x);
int interest (int p, int r, int t);
void swap (int x, int y);
int tables (int i, int j, int k);
int distance (double x, double y, double z);
int speed (double x, double y, double z);
int power (double x, double y, double z);
int sqroot (double x, double y, double z);
int converter (double x, double y, double z);
int inr (double x, double y, double z);
int usd (double x, double y, double z);
int mtrs(double x, double y, double z);
int main () {
int a, b;
double x, y, p, q, m1, m2, m3, m4, m5, r, h, t, i, j, k, z, ans;
cout << "MAIN MENU";
cout << "\n 1. Sum of Natural nos.";
cout << "\n 2. Factorial";
cout << "\n 3. Greatest number among 3";
cout << "\n 4. Percentage(5 subjects)";
cout << "\n 5. Volume of cylinder";
cout << "\n 6. Vote age checker";
cout << "\n 7. interest_calculator";
cout << "\n 8. Swapping nos.";
cout << "\n 9. Table of a number.";
cout << "\n 10. Distance calculator";
cout << "\n 11. Speed calculator";
cout << "\n 12. Calculate the power of a number";
cout << "\n 13. Square root calculator";
cout << "\n 14. Converter";
cout <<
"\n \n Select one of the above option typing the serial number of the
same";
cin >> a;
switch (a) {
case 1:
cout << "Enter any number";
cin >> x;
ans = sum(x);
cout << ans;
break;
case 2:
cout << "Enter any number";
cin >> y;
ans = factorial(y);
cout << ans;
break;
case 3:
cout << "Enter 3 numbers";
cin >> p >> q >> r;
ans = greatest(p, q, r);
cout << ans << " is the biggest number";
break;
case 4:
cout << "Enter marks of 5 subjects ";
cin >> m1 >> m2 >> m3 >> m4 >> m5;
ans = percentage(m1, m2, m3, m4, m5);
cout << ans << "%";
break;
case 5:
cout << "enter value of radius" << "\n";
cin >> r;
cout << "Enter value of height" << "\n";
cin >> h;
ans = formula(r, h);
cout << ans;
break;
case 6:
cout << "Enter your age" << "\n";
cin >> x;
ans = voter_age(x);
break;
case 7:
cout << "Enter principle amount " << "\n";
cin >> p;
cout << "Enter rate " << "\n";
cin >> r;
cout << "Enter time " << "\n";
cin >> t;
ans = interest(p, r, t);
cout << ans;
break;
case 8:
cout << "Enter 1st number.";
cin >> x;
cout << "Enter 2nd number";
cin >> y;
break;
case 9:
cout << "Enter a number to display its table";
cin >> i;
ans = tables(i, j, k);
cout << ans;
break;
case 10:
cout << "Enter speed in km/hr" << endl;
cin >> x;
cout << "Enter time in hours" << endl;
cin >> y;
ans = distance(x, y, z);
cout << ans << "km";
break;
case 11:
cout << "Enter distance in km" << endl;
cin >> x;
cout << "Enter time in hours" << endl;
cin >> y;
ans = speed(x, y, z);
cout << ans << "km/hr.";
break;
case 12:
cout << "Enter a number" << endl;
cin >> x;
cout << "Enter the power" << endl;
cin >> y;
ans = power(x, y, z);
cout << ans;
break;
case 13:
cout << "Enter a number" << endl;
cin >> x;
ans = sqroot(x, y, z);
cout << ans;
break;
case 14:
cout << "Select one of the following" << endl;
cout << "\n a. Currency";
cout << "\n b. Distance";
cout << "\n c. mass";
cout << "\n d. temperature" << endl;
cin >> b;
switch (b) {
case 1:
cout << "Select one of the following:" << endl;
cout << "\t 1. For INR to USD type " << endl;
cout << "\t 2. For USD to INR type " << endl;
cin >> b;
switch (b) {
case 1:
cout << "Enter amount in INR" << endl;
cin >> y;
ans = inr(x, y, z);
cout << ans << "$";
break;
case 2:
cout << "Enter amount in USD" << endl;
cin >> y;
ans = usd(x, y, z);
cout << ans << "Rs.";
break;
}
break;
case 2:
cout << "Slect one of the following" << endl;
cout << "\t Mtrs to kms and cms" << endl;
cout << "\t Kms to Mtrs and cms" << endl;
cout << "\t Cms to Mtrs and Kms" << endl;
break;
case 3:
cout << "Select one of the following" << endl;
cout << "\t Kgs to grams and pounds" << endl;
cout << "\t Grams to Kgs and Pounds" << endl;
cout << "\t Pounds to kgs and grams" << endl;
break;
case 4:
cout << "Select one of the following" << endl;
cout << "\t Celcius to Farenhite and Kelvin" << endl;
cout << "\t Farenhite to Celcius and Kelvin" << endl;
cout << "\t Kelvin to Celcius and Farenhite" << endl;
break;
}
break;
default:
cout << "please enter correct option";
}
}
int sum (int x)
{
int i, sum = 0;
for (i = 1; i <= x; i++)
sum = sum + i;
return (sum);
}
int factorial (int y)
{
int i, fact = 1;
for (i = 1; i <= y; i++)
fact = fact * i;
return (fact);
}
int greatest (int p, int q, int r)
{
int s;
if ((p > q) && (p > r))
s = p;
else if ((q > p) && (q > r))
s = q;
else if ((r > p) && (r > q))
s = r;
return (s);
}
int percentage (int m1, int m2, int m3, int m4, int m5)
{
int s, q;
s = m1 + m2 + m3 + m4 + m5;
q = s / 5;
return (q);
}
int formula (int r, int h)
{
return (r * r * h * 3.14);
}
int voter_age (int x)
{
if (x >= 18)
cout << "eligible to vote";
else if (x < 18)
cout << "Not eligible to vote, wait for " << 18 - x << " years";
return (x);
}
int interest (int p, int r, int t)
{
return (p * r * t) / 100;
}
void swap (int x, int y)
{
x = x + y;
y = x - y;
x = x - y;
cout << "Value of x is " << x << "Value of y is " << y;
}
int tables (int i, int j, int k)
{
for (j = 1; j <= 10; j++)
{
k = i * j;
cout << i << "*" << j << "=" << k << "\n";
}
return (k);
}
int distance (double x, double y, double z)
{
z = x * y;
return (z);
}
int speed (double x, double y, double z)
{
z = x / y;
return (z);
}
int power (double x, double y, double z)
{
z = pow (x, y);
return (z);
}
int sqroot (double x, double y, double z)
{
z = sqrt (x);
return (z);
}
int inr (double x, double y, double z)
{
z = y * 69.70;
return (z);
}
int usd (double x, double y, double z)
{
z = (1 / 69.70) * y;
return (z);
}
int mtrs(double x, double y, double z)
{
z = (1/1000)*y;
return(z);
}
This code is my school project in which we were asked to create functions using switch. Everything is working fine except the outputs from converter(in the 1st switch case) or any other program which has to give decimal outputs.
On selecting converter from the menu, all the operations are programmed to get output in decimals but it is rounding off the numbers.
Be aware that integral types (char, unsigned int, (u)int<n>_t, size_t) all can only hold integral values. So if you assign them the value of some floating point type, you always lose the decimals.
Let's take distance as example:
int distance (double x, double y, double z)
{
z = x * y; // distance calculated as double!
return (z); // double is cast to int -> you lose the decimals
}
If you want to keep the decimals, return a floating point type:
double distance (double x, double y, double z);
// ^^
There are some other issues, though:
At first, don't use parentheses on return values!!! They have special meaning (creating a reference) and might give you unexpected results:
decltype auto distance (double x, double y, double z)
// ^ (!)
{
return (z);
}
Here, return type is deduced, and it will get a reference to the local variable z, so you end up in undefined behaviour!
Then why do you pass z as parameter at all? You don't ever use it, so make it a local variable instead:
double distance (double x, double y)
{
double z = x * y;
return z;
}
or even shorter, don't use an intermediate variable at all and return directly (prefer this style on short calculations):
return x * y;
Sometimes, you want to have additional output parameters, then you can pass these as parameters – but to be able to receive any value outside the function, you need to pass them as either reference or pointer. Prefer references if values always have to be provided, pointers only if nullptr is considered valid input as well.
int distance (double x, double y, double& z)
// ^ (!)
{
z = x * y;
return z;
}
// use:
double distance;
int rounded = distance(10.12, 12.10, distance);
In this example, you have two result values, the distance calculated (with decimals) in the double variable and the one with decimals cut away in the int variable. Be aware that there might be overflow when the double is converted to int!
Above is a rather bad example, as output is redundant, you'd do things like these if one of the outputs has different/independent meaning:
int distance (double x, double y, double& z)
{
// check input variables x and y
if(...)
{
return INVALID_PARAMETERS; // assuming you have an enum or a #define for
}
// calculations and other checks, different return values for different errors
z = x * y;
return SUCCESS;
}
This has a bit of C programming style, in C++, think of if throwing some exception possibly is more appropriate. An alternative approach to having output parameters is returning a struct or class – think of returning 2D or 3D coordinates in a struct 'Point' or complex results with real and imaginary part in a struct – well, guess – 'Complex' (be aware that there already is std::complex, though).
In addition to change return type from int to double...
Try to run with fixed and setprecision:
fixed to not remove extra 0 and setprecision to cut after some amount of decimal digits after decimal point.
for example:
#include <iomanip> //add this include
int main()
{
cout<< fixed;
double x = sum(3);
cout<<setprecision(5)<<x;
return 0;
}
/unspecified/ setprecision (int n);
Set decimal precision
Sets the decimal precision to be used to format floating-point values on output
operations.
Behaves as if member precision were called with n as argument on the
stream on which it is inserted/extracted as a manipulator (it can be
inserted/extracted on input streams or output streams).
This manipulator is declared in header <iomanip>.
i have this program assignment and one part of it is trying to find the max power a number will go to(x) without exceeding a number the user inputs it not to exceed(y). we are using it in a function. this is the whole program and what i have for max power it just keeps returning 0. it is the int maxpower(int x, int y) function i am trying to figure out
#include <iostream>
#include <cmath>
using namespace std;
// meunue where you can get your options from
void menue() {
cout << "choose the following options:" << endl;
cout << "1) Power of x raised by y." << endl;
cout << "2) Find the max power a number can be raised to." << endl;
cout << "3) Print out a number with its digits in reversed order." << endl;
cout << "4) Sum of integers from 1 to n." << endl;
cout << "5) Product of integers from 1 to n." << endl;
cout << "6) Quit" << endl;
}
//functions for finding the power usign recursion
int Power(int a, int b) {
int x = 1, i;
for (i = 1; i <= b; i++) {
if (b == 0) {
return Power(a, b--);
}
else {
x = x * a;
}
}
return x;
}
int maxpower(int n, int max_value) {
int temp = temp * n;
if (temp > max_value)
return 0;
else return maxpower(n, max_value + 1);
}
int reverse(int number) {
int lastDigit, numberOfDigits, sign = 1;//sets the sign equal to one
// if number is less than 0 returns 0
if (number < 0) {
return 0;
}
else
//if a number is under 10 than it can not be switched so you times the number by 10 and switch it.
if (number < 10)
return number * sign;
lastDigit = number % 10;
number = number / 10;
numberOfDigits = log10(number) + 1;
//recursive statement that calls the function
return (lastDigit * pow(10, numberOfDigits) + reverse(number)) * sign;
}
//finding the sum
int sum(int n) {
if (n != 0) {
return n + sum(n - 1);//recursive statement
}
else {
return n;
}
}
//finding the product
int product(int n) {
int temp;
if (n <= 1) {
return 1;
}
else {
temp = n * product(n - 1);
// recursive statement setting temp == to recursive statement
return temp;//returning temp
}
}
int main() {
int a;
int x;
int y;
int length = 0;
int temp;
int results;
// calls menue and get prints all the options
do {
menue();
//inserts the choice
cin >> a;
cout << "you choose:" << a << endl;//prints the choice out.
//switch statement that will take account for the number you choose and prints the results
switch (a) {
case 1:
cout << "enter the number to raise" << endl;
cin >> x;
cout << " enter the power to raise to: " << endl;
cin >> y;
Power(x, y);
cout << "the result is:" << Power(x, y) << endl;
break;
case 2:
cout << "Enter the number to raise:" << endl;
cin >> x;
cout << "Enter the number not to exceed:" << endl;
cin >> y;
maxpower(x, y);
cout << "the result is:" << maxpower(x, y) << endl;
break;
case 3:
cout << " enter numbers to be reversed by: " << endl;
cin >> x;
temp = x;
while (temp != 0) {
length++;
temp = temp / 10;
}
reverse(x);
cout << "the result is:" << reverse(x) << endl;
break;
case 4:
cout << "enter the number to sum to: " << endl;
cin >> x;
sum(x);
cout << "the result is:" << sum(x) << endl;
break;
case 5:
cout << "enter the number to multiply to:" << endl;
cin >> y;
product(y);
cout << "the result is:" << product(y) << endl;
break;
case 6:
cout << "good bye!!" << endl;
break;
}
} while (a != 6);
return 0;
}
I don't think it's necessary to use recursion for this problem. Moreover, recursion is creating a lot of overhead while solving it with a loop works just fine. Do you have to use recursion? If so, then disregard this answer :p. But you'll find below a solution that will work.
Note the #include <math.h> bit - you need that to use pow(base, exponent).
Also, while(true) is definitely not the best practice, but as long as you have sufficient checks to get out of the loop properly then you're ok. Hence the max_iteration and the actual return statement that you're looking for.
Best of luck!
#include <iostream>
#include <math.h>
int maxpower(int n, int max_value) {
if ( n > max_value ) return 0;
int previous, current = 1;
int max_iteration = 0;
while (true) {
if (max_iteration >= 1000) return -1;
if (pow(n, current) > max_value) {
return previous;
}
previous = current;
current++;
max_iteration++;
}
}
int main() {
int x;
int y;
int result;
std::cout << "Enter the base: ";
std::cin >> x;
std::cout << "Enter the max number x^pow should not exceed: ";
std::cin >> y;
result = maxpower(x, y);
if (result == -1) {
std::cout << "Max iteration reached." << std::endl;
}
else {
std::cout << result << " is the maximum power such that " << x << "^" << result << " does not exceed " << y << std::endl;
}
return 0;
}
As an example of output:
If x = 2 and y = 32, the program will return 5 as the max power (i.e. 2^5 = 32 and is not greater than, but 2^6 > 32).
EDIT:
I realized after I posted that all of your functions are recursive, so perhaps that's a requirement for your assignment. Anyway, below is a recursive solution:
int maxpower_rec_helper(int n, int power, int max_value) {
if (pow(n, power) > max_value) return power - 1;
return maxpower_rec_helper(n, power + 1, max_value);
}
int maxpower_rec(int n, int max_value) {
if ( n > max_value ) return 0;
return maxpower_rec_helper(n, 1, max_value);
}
You'll need a helper function to give the initial power 1, and so as not to disturb your max_value.
return power - 1; is essentially the same thing as return previous; in the iterative example above.
I've been working for a couple hours trying to figure out what I'm doing wrong. All I need to do is find one root from a polynomial represented by an array using Newton's method. The two functions (polyval and polyder) seem to be giving me the right answers, and I feel that the main code is correctly doing Newton's method. I was hoping someone experienced could give me some advice.
#include <iostream>
#include <cmath>
using namespace std;
float polyval(float*, int, float);
void polyder(float*, int, float*);
int main(void) {
int n;
float x=-1,f;
float tol=pow(10,-5);
cout << "Enter polynomial order:" << endl;
cin >> n;
float* p=new float[n+1];
float* dp=new float[n];
cout << "Enter coefficients, starting with the highest power:" << endl;
for (int k=0;k<n+1;k++) {
cin >> p[k];
}
polyder(p,n,dp);
f=polyval(p,n,x);
while (fabs(f)>tol) {
x=x-f/polyval(dp,n,x);
f=polyval(p,n,x);
cout << x << endl;
cout << f << endl;
}
cout << "A real root is at x= " << x << endl;
cout << "To verify: p(" << x << ") = " << polyval(p,n,x) << endl;
return 0;
}
float polyval(float* p, int n, float x) {
float px;
px=0;
for (int k=0;k<n+1;k++) {
px=px+p[k]*pow(x,n-k);
}
return px;
}
void polyder(float* p, int n, float* dp) {
for(int k=0;k<n;k++) {
dp[k] = p[k+1] * (k+1);
}
}
Your call to polyval(dp,n,x) will access beyond the allocated space for dp, which has n entries and not the requred n+1.
I have a simple program that is calculating factorials, permutations and combinations. I feel good about my math but for whatever reason I cannot get this program to execute. Full disclosure I am new student to C++. Here is my code:
#include <iostream>
using namespace std;
int factorial(int);
int permutations(int, int);
int combinations (int ,int);
void perms_and_combs(int, int, int&, int&);
int numPerms;
int numCombs;
int main() {
int factorialVal;
cout << "enter an int!\n";
cin >> factorialVal;
cout << "The factorial of " << factorialVal << " is " << factorial(factorialVal) << endl;
int permVal1;
int permVal2;
do {
cout << "Input a two values: ";
cin >> permVal1;
cout << ", ";
cin >> permVal2;
} while ( permVal1 < 0 || permVal2 > permVal1);
cout << "test"; // This line doesn't get executed
perms_and_combs(permVal1, permVal2, numPerms, numCombs);
cout << "Number of permutations: "<<numPerms << ". Number of combinations: " << numCombs;
return 0;
}
int factorial(int n) {
int product = 1;
for (int i = 1; i <= n; i++) {
product *= i;
}
return product;
}
int permutations (int n, int k) {
int result;
int denominator = n-k;
cout << denominator;
result = (factorial(n)/factorial(denominator));
return result;
}
int combinations (int n, int k) {
int result;
result = permutations(n, k) * (1/factorial(k));
return result;
}
void perms_and_combs(int n, int k, int& numPerms, int& numCombs) {
numPerms = permutations(n, k);
numCombs = combinations(n, k);
return;
}