#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>.
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
Im trying to make a simple converter using reference to convert between cartesian and polar the problem is it gives me wrong answers and sometimes 0 ,0 . I want to know what's the problem and how can i fix it .
this is the code :
#include <iostream>
#include <cmath>
using namespace std;
void cartesianToPolar(int x,int y,float &r,float &q ) {
r = sqrt(x * x + y * y); q = atan(y / x);
}
void polarToCartesian(float r, float q, int &x, int &y) {
x = r * cos(q); y = r * sin(q);
}
int main() {
int cevap ;
int x = 0 , y = 0 ,xx = 0 , yy = 0;
float r = 0 , q = 0 , rr = 0 , qq = 0 ;
cout << "Choose please....." << endl;
cout << "1-Cartesian -> polar "<<endl;
cout << "2-polar ->Cartesian " << endl;
cin >> cevap;
if(cevap==1){
cout << "enter x value: " ;
cin >> x;
cout << "enter y value: " ;
cin >> y;
cartesianToPolar(x,y,rr,qq);
cout << "r: " << rr << " " << "Q: " << qq << endl;
}
else if (cevap==2)
{
cout << "enter r value : ";
cin >> rr;
cout << "enter Q value: ";
cin >> qq;
polarToCartesian(r, q, xx, yy);
cout << "x: " << xx << " " << "y: " << yy << endl;
}
return 0;
}
Results of both of your functions should be floats, not ints:
void cartesianToPolar(float x, float y, float &r, float &q ) {
r = sqrt(x * x + y * y); q = atan(y / x);
}
void polarToCartesian(float r, float q, float &x, float &y) {
x = r * cos(q); y = r * sin(q);
}
The values you were computing were correct, but the result was converted to integers afterwards. Conversion to int happens by trunctation, that is, 0.1 and 0.9 all become just 0.
You also had a typo in your polar to cartesian conversion in the main. Used the wrong variable. Correct is:
polarToCartesian(rr, qq, xx, yy);
Following #Yunnosch comment, you should use atan2() rather than atan(). Detailed explanation can be found here
I need help with inputting a search array. I tried putting a binary search but I can't get it to work. everything else works up until I put the value I am searching for in the array, then it just crashes.
How it suppose to work:
input 2 coordinates with a value each
then it calculates the distance between them
then it suppose to let user search the coordinates for a value and state if found which coordinate it is at.
Thanks
#include "stdafx.h"
#include <iostream>
#include <iomanip> //for setprecision
#include <math.h>
#include <cstdbool>
#include <cstdlib> // Needed for rand and srand
#include <ctime> // Needed for the time function
using namespace std;
//Function Prototypes
void processThroughArray(int[][10][10], int, int, int, int, int, int);
int searchArray(int[][10][10], int, int, int, int, int, int, int, int);
const int SIZE = 10;
int main()
{
// establish array and set all values to 0
int myArray[10][10][10] = { 0 };
// establish x and y position markers
int x = 0;
int y = 0;
int z = 0;
int x2 = 0;
int y2 = 0;
int z2 = 0;
// establish input for x and y from the user
int xInput = 0;
int yInput = 0;
int zInput = 0;
int xInput2 = 0;
int yInput2 = 0;
int zInput2 = 0;
// variable for value entered
int inputValue = 0;
int inputValue2 = 0;
double distance = 0;
int searchValue;
int result;
// Get the user's value and coordinate
cout << "\nPlease enter the x coordinate ";
cin >> xInput;
cout << "\nPlease enter the y coordinate ";
cin >> yInput;
cout << "\nPlease enter the z coordinate ";
cin >> zInput;
cout << "\nPlease enter the value to place in " << xInput << "," << yInput << "," << zInput << " ";
cin >> inputValue;
// Get the user's ending value and coordinate
cout << "\nPlease enter the ending x coordinate ";
cin >> xInput2;
cout << "\nPlease enter the ending y coordinate ";
cin >> yInput2;
cout << "\nPlease enter the ending z coordinate ";
cin >> zInput2;
cout << "\nPlease enter the value to place in " << xInput2 << "," << yInput2 << "," << zInput2 << " ";
cin >> inputValue2;
// place the value in the coordinate
myArray[xInput][yInput][zInput] = inputValue;
cout << "\nYou have successfully placed the value " << inputValue << " in coordinate " << xInput << ", " << yInput << ", " << zInput << " ";
myArray[xInput2][yInput2][zInput2] = inputValue2;
cout << "\nYou have successfully placed the value " << inputValue2 << " in coordinate " << xInput2 << ", " << yInput2 << ", " << zInput2 << " ";
//Function performing for loop
processThroughArray(myArray, x, y, z, x2, y2, z2);
//calculate distance between the two coordinates
distance = sqrt(pow(xInput2 - xInput, 2.0) + pow(yInput2 - yInput, 2.0) + pow(zInput2 - zInput, 2.0));
cout << "\nThe distance between " << xInput << "," << yInput << "," << zInput << " and " << xInput2 << "," << yInput2 << "," << zInput2 << " is ";
cout << setprecision(4) << distance << endl;
// indicate end of array processing
cout << "\nArray Processed" << endl;
//User inputs value to search for
cout << "Enter the value you wish to look for: ";
cin >> searchValue;
result = searchArray(myArray, SIZE, searchValue, x, y, z, x2, y2,z2);
//If results contains a -1 the value not found
if (result == -1 )
{
cout << "That number does not exists in the array.\n";
}
else
{
cout << "\nValue " << searchValue;
cout << " is located at position: " << result << endl;
}
system("pause");
return 0;
}
//**************************************************************************
// Definition of function processThroughArray: Process through the array *
//the for loop *
//**************************************************************************
void processThroughArray(int myArray[][10][10], int x, int y, int z, int x2, int y2, int z2)
{
for (int x = 0, x2 = 0; x<10, x2 < 10; x++, x2++)
{
for (int y = 0, y2 = 0; y<10, y2 < 10; y++, y2++)
{
for (int z = 0, z2 = 0; z< 10, z2 < 10; z++, z2++)
{
// Display the value of the coordinate
cout << "\nCordinate " << x << ", " << y << ", " << z << " value is " << myArray[x, x2][y, y2][z, z2];
}
}
}
}
//**************************************************************************
// Definition of function searchArray: search array for the value input *
// *
//**************************************************************************
int searchArray(int myArray[][10][10], int size, int value,int x, int y, int z, int x2, int y2, int z2)
{
int index = 0;
int position = -1;
bool found = false;
while (index < size && !found)
{
if (myArray[index][index][index] == value)
{
found = true;
position = index;
}
index++;
}
return position;
}
You're defining SIZE as 1000, and you're passing it to searchArray():
const int SIZE = 1000;
// ...
searchArray(myArray, SIZE, searchValue);
You are doing the following in searchArray():
int searchArray(int myArray[][10][10], int size, int value)
{
int first = 0,
last = size - 1,
Since size is 1000, you are setting "first" to 0 and "last" to 999.
Then, you're doing the following (leaving out some irrelevant stuff):
middle = (first + last) / 2;
if (myArray[middle][middle][middle] = value)
So, let's take out a piece of paper, and a pencil. Since "first" is 0, and "last" is 999, this sets "middle" to 449.
So, we have two problems here:
1) You're assigning using the "=" operator, instead of comparing using "==", which appears to be your intent.
2) You are assigning a value to myArray[449][449][449]. Unfortunately, your array is much, much smaller:
int myArray[10][10][10] = { 0 };
Trying to access the 449th's element of the 449th array of ten elements, of the 449th array of ten arrays of ten elements, is not going to work very well. Even if you were comparing, or assigning something, either way this is undefined behavior, and an almost guaranteed crash.
EDIT: Global variables are restricted as part of the assignment (Forgot to mention this).
The program is meant to calculate a projected population every year for a specified number of years. Here is the equation:
N = P(1 + B)(1 - D)
Where N is the new population size, P is the previous population size, B is the birth rate, and D is the death rate. B and D are decimals.
So my problem is that I can only get the first iteration's result, and I don't know how to update the result so that it is multiplied by the (1 + B) and (1 - D). My guess is that it has to do with one of the combined assignment operators, but I haven't had success.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int get_pop();
int get_numYears();
double get_annBirthRate();
double get_annDeathRate();
double pop_new(int& A, double& B, double& C, double& D);
int main()
{
int P,
num,
Y;
double B,
D,
N;
P = get_pop();
B = get_annBirthRate();
D = get_annDeathRate();
Y = get_numYears();
for (num = 1; num != Y; num++)
{
N = pop_new(P, B, D, N);
cout << "\n\nThe projected population for the end of year " << num << " is " << N << endl;
cin.ignore();
}
return 0;
}
int get_pop()
{
int pop;
cout << "Enter the starting population:" << endl;
cin >> pop;
while (pop < 2)
{
cout << "\n\nError - starting population cannot be less than 2:" << endl;
cin >> pop;
}
return pop;
}
double get_annBirthRate()
{
double annBirthRate;
cout << "\n\nEnter the annual birth rate \n(a positive percentage in decimal form):" << endl;
cin >> annBirthRate;
while (annBirthRate < 0)
{
cout << "\n\nError - annual birth rate cannot be negative:" << endl;
cin >> annBirthRate;
}
return annBirthRate;
}
double get_annDeathRate()
{
double annDeathRate;
cout << "\n\nEnter the annual death rate \n(a positive percentage in decimal form):" << endl;
cin >> annDeathRate;
while (annDeathRate < 0)
{
cout << "\n\nError - death rate cannot be negative:" << endl;
cin >> annDeathRate;
}
return annDeathRate;
}
int get_numYears()
{
int numYears;
cout << "\n\nEnter the number of years to display:" << endl;
cin >> numYears;
while (numYears < 0)
{
cout << "\n\nError - number of years cannot be less than 1:" << endl;
cin >> numYears;
}
return numYears;
}
double pop_new(int& P, double& B, double& D, double& N)
{
N = P * (1 + B) * (1 - D);
return N;
}
The values P, B, and D do not change.
Make it:
double pop_new(int P, double B, double D)
{
double N = P * (1 + B) * (1 - D);
return N;
}
and:
P = pop_new(P, B, D);
cout << "\n\nThe projected population for the end of year "
<< num << " is " << P << endl;
Note: You do not need to pass references (and if, you should have passed const double&)
I want to simplify a fraction in my application. The fraction is like,
x/y where x and y are integers.
I want to simplify the fraction to its simplest form.
Can anyone please give me hints how to do it.
Thanks in advance.
Compute the greatest common divisor for x and y
Divide both of them by the GCD
Euclid's algorithm is an easy way to compute the GCD.
Divide both by gcd(x,y)
The Binary GCD algorithm is a fast way to compute the GCD on a computer.
#include<iostream>
using namespace std;
struct fraction
{
int n1, d1, n2, d2, s1, s2;
};
void simplification(int a,int b)
{
bool e = true;
int t; int z;
for (int i = (a*b); i > 1;i--)
{ if ((a%i==0)&&(b%i==0))
{
t = a / i;
z = b / i;
}
else
{
e = false;
}
}
cout << "simplest form=" << t << "/" << z << endl;
}
void sum(int num1, int deno1, int num2, int deno2)
{
int k,y;
k = num1* deno2 + num2*deno1;
y = deno2*deno1;
cout << "addition of given fraction = " << k << "/" << y << endl;
simplification(k, y);
}
void sub(int num1, int deno1, int num2, int deno2)
{
int k, y;
k = num1*deno2 - num2*deno1;
y = deno1*deno2;
cout << "Substraction of given fraction = " << k << "/" << y << endl;
}
void mul(int num1, int deno1, int num2, int deno2)
{
int k, y;
k = num1*num2;
y = deno1*deno2;
cout << "multiplication of given fration= " << k<< "/" <<y; cout<< endl;
simplification(k, y);
}
void div(int num1, int deno1, int num2, int deno2)
{
int k, y;
;
k = num1*deno1;
y = deno1*num2;
cout << "division of given fraction" << k << "/" << y << endl;
simplification(k, y);
}
int main()
{ fraction a;
cout << "enter numirator of f1=";cin >> a.n1;
cout << "enter denominator of f1=";cin >> a.d1;
cout << "enter numirator of f2=";cin >> a.n2;
cout << "enter denominator of f2=";cin >> a.d2;
cout << "f1= " << a.n1 << "/" << a.d1 << endl;
cout << "f2= " << a.n2 << "/" << a.d2 << endl;
mul(a.n1, a.d1, a.n2, a.d2);
div(a.n1, a.d1, a.n2, a.d2);
sub(a.n1, a.d1, a.n2, a.d2);
sum(a.n1, a.d1, a.n2, a.d2);
system("pause");
}