How to evaluate operations then print a message - c++

Take 4 variables from user w, x ,y ,z.
If w ‘x’ y = z print “You are right” otherwise, print
“ERROR
Below is the code I created for this problem, but it seems there is something wrong.
#include<iostream>
using namespace std;
void calculate(int w, char x, int y, int z)
{
if (x == '+') {
int z = w + y ;
cout << "You are right" <<endl;
}
else if (x == '-') {
int z = w - y ;
cout << "You are right" << endl;
}
else if (x == '*') {
int z = x * y;
cout << "You are right" << endl;
}
else
cout << "Error!" << endl;
}
int main()
{
int w, y, z;
char x;
cout << "Enter values for w, x, y, and z: " << endl;
cin >> w >> x >> y >> z;
cout << endl;
calculate(w, y, x, z);
return 0;
}

void calculate(int w, char x, int y, int z)
{
if (x == '+') {
int z = w + y ;
cout << "You are right" <<endl;
}
else if (x == '-') {
int z = w - y ;
cout << "You are right" << endl;
}
else if (x == '*') {
int z = x * y;
cout << "You are right" << endl;
}
else
cout << "Error!" << endl;
}
If you look closely int z = w + y is wrong as you are already taking z as a function parameter.
The correct statement, however, would be z = w + y.
The second thing, you need to remove int z from your function parameters, but declare and define it inside the function body. This is because when you pass z from main(), you aren't really passing the variable z. But merely the value of it which will get copied into int z in calculate.
Passing z as a reference
If you want the z in your main to update, you shall pass the value by reference.
void calculate(int w,char x,int y,int& z)
{
//updating z
}
Now, if you apply any change to z in calculate(), it will also appear your main().
Another solution is to to return int from the function and assign to the variable z in main().
#include <iostream>
int calculate(int w,int y,char x)
{
switch(x)
{
case '+':
std::cout << "You are right!\n";
return w+y;
case '-':
std::cout << "You are right!\n";
return w-y;
case '*':
std::cout << "You are right!\n";
return w*y;
default:
std::cout << "You are wrong!\n";
break;
}
}
int main()
{
int w = 5;
int y = 10;
char x = '+';
int z = calculate(w,y,x);
std::cout << z;
return 0;
}

Related

(C++) How to pass a local variable from main to another function's body if the value is already inputed by user in main?

The only way I was able to solve this is by creating global variables like float x, y; and then using those throughout the program. I am very new to programming as it's obvious, but I've heard that is usually a bad practice to create global variables.
My guess is that the problem occurs in the void completeOperation(int z){} function as error messages basically state that both the variable x and y haven't been declared. When I declare them in that scope, it asks me to give them a value while I need a user to input the said value in main.
How can I make this work? Forgive me for having to put the whole code up. It's tiny.
#include <iostream>
using namespace std;
void createMenu();
void completeOperation(int z);
float add(float x, float y);
float subtract(float x, float y);
float multiply(float x, float y);
float divide(float x, float y);
float greaterNumber(float x, float y);
float lesserNumber(float x, float y);
int main()
{
float x, y;
cout << "Enter the first real number value." << endl;
cin >> x;
cout << "Enter the second real number value." << endl;
cin >> y;
createMenu();
int z;
cin >> z;
completeOperation(z);
system("pause");
}
void createMenu()
{
cout << "\nChoose a desired arithmetic operation by entering a number from 1 to 6. \n\n";
cout << "1.) Addition \n2.) Subtraction \n3.) Multiplication \n4.) Division \n5.) Bigger number \n6.) Smaller number" << endl;
}
void completeOperation(int z)
{
switch (z)
{
case 1:
cout << "\nAddition: " << add(x, y) << endl;
break;
case 2:
cout << "\nSubtraction: " << subtract(x, y) << endl;
break;
case 3:
cout << "\nMultiplication: " << multiply(x, y) << endl;
break;
case 4:
cout << "\nDivision: " << divide(x, y) << endl;
break;
case 5:
cout << "\nBigger number: " << greaterNumber(x, y) << endl;
break;
case 6:
cout << "\nSmaller number: " << lesserNumber(x, y) << endl;
break;
}
}
float add(float x, float y)
{
return (x + y);
}
float subtract(float x, float y)
{
return (x - y);
}
float multiply(float x, float y)
{
return (x * y);
}
float divide(float x, float y)
{
return (x / y);
}
float greaterNumber(float x, float y)
{
if (x > y)
{
return x;
}
else return y;
}
float lesserNumber(float x, float y)
{
if (x < y)
{
return x;
}
else return y;
}

Try catch using a function for negative integers

So basically I am trying to get it to stop repeating. If I enter numbers correctly it works fine. If I enter negative numbers which are not allowed and needs a try-catch exception it keeps repeating and won't stop asking for numbers.
All I have is this source file for the code and I am trying to make a function for main.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void gcd(int x, int y);
int main()
{
int x;
int y;
cout << "Please enter two integer values" << endl;
cin >> x;
cin >> y;
gcd(x, y);
return 0;
}
void gcd(int x, int y)
{
int gcd;
int s = 0;
while (s == 0)
{
try
{
if (x < 0 || y < 0)
throw 1;
else
{
s == 1;
break;
}
}
catch (int x)
{
cout << "Wrong negative input please type in two Positive integers" << endl;
cin >> x >> y;
continue;
}
}
for (int i = 1; i <= x && i <= y; i++)
{
if (x % i == 0 && y % i == 0)
gcd = i;
}
cout << "The gcd of x: " << x << " and y: " << y << " is: " << gcd << endl;
}
If you don't want your function gcd() to be called with negative values, throw a std::invalid_argument exception. It is not the business of gcd() to request user input. Validate the input in main() before you call gcd().
#include <limits>
#include <stdexcept>
#include <iostream>
int gcd(int, int);
int main()
{
int x, y;
while (std::cout << "Please enter two positive integers: ",
!(std::cin >> x >> y) || x < 0 || y < 0)
{
std::cerr << "Input error :(\n\n";
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
std::cout << "The gcd of x: " << x << " and y: " << y << " is: " << gcd(x, y) << "\n\n";
}
int gcd(int x, int y)
{
if (x < 0 || y < 0)
throw std::invalid_argument("No negative arguments to gcd(), please :(");
return y == 0 ? x : gcd(y, x % y);
}
You can (and perhaps should) remove the logic from gcd function and instead place it where you get your input from user, that is, in main. Also, state the requirements up front. For example:
int main()
{
int x;
int y;
cout << "Please enter two positive integer values" << endl;
cin >> x;
cin >> y;
if (x < 0 || y < 0)
{
cout << "Wrong negative input please type in two Positive integers" << endl;
return 0;
}
gcd(x, y);
return 0;
}
Now, you can place assertions in gcd to enforce no negative values get in:
void gcd(int x, int y)
{
assert(x >= 0);
assert(y >= 0);
// ...
}

Unable to get decimal output in c++ code.

#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>.

Undeclared identifier in c++

I want to print three number from maximum to minimum for 3 numbers, when I try to compile this code it shows me this error C2065 "function parameter :Undeclared identifier function parameter"for every function arguments . other error is C 2062 type "int" unexpected.
Here is my code
#include "stdafx.h"
#include <iostream>
using namespace std;
int max, min;//making global variable of max and min
void numMax(int x, int y, int z);//finding maximum number
void numMin(int x, int y, int z);/finding minimum number
int main()
{
int x, int y, int z;
int middle = 0;
cout << "This program will take 3 number and print them from minimum to maximum" << endl;
cout << "_________________" << endl;
cout << "Pleas enter three number" << endl;
cout << "num1 =";cin >> x;cout << endl << "\n";
cout << "num2 =";cin >> y;cout << endl << "\n";
cout << "num3 =";cin >> z;cout << endl << "\n";
numMax(x, y, z);
numMin(x, y, z);
if (x<max & x>min)
{
middle = x;
}
if (y<max & y>min)
{
middle = y;
}
if (z<max & z>min)
{
middle = z;
}
cout <<"ordered numbers are : "<< min << "\t"<< middle << "\t" <<max ;
return 0;
}
void numMAx(int x, int y, int z)
{
int max;
max = x > y ? x : y;
max = z > max ? z : max;
cout << max;
}
void numMin(int x, int y, int z)
{
int min;
min = x < y ? x : y;
min = min<z ? min : z;
cout << min;
}
first I have defined my functions, then in main function I have passed parameter to function argument then I have mentioned my numMax and numMin fuctions to excute their task. finally I have used if statement for determining middle number. What should I do ?
int numMax (int x,int y ,int z)
{
if(x>y && x>z)
return x;
else if (y>x && y>z)
return y;
else
return z;
}
int numMin(int x,int y ,int z)
{
if(x<y && x<z)
return x;
else if (y<x && y<z)
return y;
else
return z;
}
void main()
{
int x,y,z;
int max,min;
clrscr();
cout<<"\n Enter 3 Number: \n";
cout<<"1st Num: ";cin>>x;
cout<<"2nd Num: ";cin>>y;
cout<<"3rd Num: ";cin>>z;
max = numMax(x,y,z);
min = numMin(x,y,z);
if(x<max && x>min)
{
middle=x;
}
else if(y<max && y>min)
{
middle=y;
}
else
middle=z;
cout<<"Number from max to min are: \n "<<numMax(x,y,z)<<" "<<numMin(x,y,z)<<" "<<middle;
}
try this

euclid's extended algorithm C ++

I'm having an issue with Euclid's Extended Algorithm. (ax+by=gcd(a,b)) I'm trying to determine both the GCD and x and y. The GCD isn't a problem but using the loop method something is going wrong with x and y. Normally one number comes up as 0 and the other is an abnormally large negative number. Code follows:
#include <iostream>
using namespace std;
main ()
{
int a,b,q,x,lastx,y,lasty,temp,temp1,temp2,temp3;
cout << "Please input a" << endl;
cin >> a;
cout << "Please input b" << endl;
cin >> b;
if (b>a) {//we switch them
temp=a; a=b; b=temp;
}
//begin function
x=0;
y=1;
lastx=1;
lasty=0;
while (b!=0) {
q= a/b;
temp1= a%b;
a=b;
b=temp1;
temp2=x-q*x;
x=lastx-q*x;
lastx=temp2;
temp3=y-q*y;
y=lasty-q*y;
lasty=temp3;
}
cout << "gcd" << a << endl;
cout << "x=" << lastx << endl;
cout << "y=" << lasty << endl;
return 0;
}
Although the question has been asked a long time ago, but the answer will help someone who were finding C++ implementation of extended euclidean algorithm.
Here is a recursive C++ implementation:
int xGCD(int a, int b, int &x, int &y) {
if(b == 0) {
x = 1;
y = 0;
return a;
}
int x1, y1, gcd = xGCD(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
return gcd;
}
Example with code:
#include <iostream>
int main()
{
int a = 99, b = 78, x, y, gcd;
if(a < b) std::swap(a, b);
gcd = xGCD(a, b, x, y);
std::cout << "GCD: " << gcd << ", x = " << x << ", y = " << y << std::endl;
return 0;
}
Input:
a = 99, b =78
Output:
GCD: 3, x = -11, y = 14
Two of your assignments are wrong they should be:
temp2 = x;
x=lastx-q*x;
lastx = temp2;
temp3 = y;
y = lasty-q*y;
lasty=temp3;
Example output with the above fixes:
Please input a
54
Please input b
24
gcd6
x=1
y=-2