return function values as pointer [duplicate] - c++

This question already has answers here:
What does the comma operator , do?
(8 answers)
How does the Comma Operator work
(9 answers)
Returning a second value through pointer or reference C++
(4 answers)
Closed 6 months ago.
Question:
Make function which will sum two integer variables (a,b) and then return result in variable rez , using pointer. Also, in the same function, return sum a+b+10 in another variable rez_a using pointer.
Well, here is the code. It returns only the first value (*p1):
#include <iostream>
using namespace std;
int vrati(int a, int b) {
int rez = a + b;
int rez_a = a + b + 10;
int* p1 = &rez;
int* p2 = &rez_a;
return *p1,*p2;
}
int main() {
int a = 4;
int b = 6;
cout << vrati(a, b);
return 0;
}

I think you are taking return too literally. I expect the function you are meant to write is this
void vrati(int a, int b, int *rez, int* rez_a) {
*rez = a + b;
*rez_a = a + b + 10;
}
int main() {
int a = 4;
int b = 6;
int rez, rez_a;
vrati(a, b, &rez, &rez_a);
cout << rez << ' ' << rez_a;
return 0;
}
This function returns values, but it doesn't use return. I can understand why you were confused.

Related

Can you store arithmetic operators in an array i,e(+, -, *, /) in C++

I want to make a program that takes 4 numbers eg.(a, b, c and d) and checks if using arithmetic operators i can make the first 3 numbers result to the fourth number, like if the input is (3, 4, 5, 23) this will check out true because
3 + 4 * 5 = 23,So i want to make an array that has the operators and use a loop to check every possible combination, Hope i made it clear.
Edit:
Its actually codeforces problem, given 4 numbers. Check whether he could get the fourth number by using the arithmetic operators (+,−,×) between the other three numbers. Knowing that an operator can be used only once. in this format ->(a□b□c=d).My question was if there is a way to make it automatic or do i have to code every possibility manually So sorry for any confusion i may have caused.
You can't store the operators in an array, but you could make wrapper functions for them and store those in an array.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
funptr arr[] = { add, sub, mul, div };
You can then call them like:
(arr[1])(2, 1) // call sub(2, 1)
The parentheses around arr[1] aren't needed in this case, but I like to put them for clarity.
No. You'd have to write a program to work this out. You could store something like function pointers to the arithmetic operators in an array, but I don't think that would help solve your problem. You'd still have to write the code to solve your problem.
Adding onto #CoffeeTableEspresso's answer, you can also put those function pointers into a map.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
std::map<char,funptr> operators = {
{'+', add},
{'-', sub},
{'*', mul},
{'/', div}};
Then you can do
operators['+'](4,7);
Which might be a bit more readable, and you can iterate through these more easily.
I thought I would submit a compete answer. This works for positive numbers. It may take a bit more work to cover all the possibilities. And it does not answer to CoffeeTableEspresso's question about precedence. But it may help with your last question about if statements.
#include <iostream>
namespace {
auto add = [](int a, int b) {return a + b; };
auto sub = [](int a, int b) {return a - b; };
auto mult = [](int a, int b) {return a * b; };
auto divd = [](int a, int b) {return b ? a / b : -1; };
std::vector<int(*)(int, int)> ops = { add,sub,mult,divd };
}
int check(int* params)
{
for (size_t i = 0; i < 4; ++i)
for (size_t j = 0; j < 4; ++j)
{
auto result = ops[i](params[0], ops[j](params[1], params[2]));
if (params[3] == result)
return result;
else
std::cout << result << std::endl;
}
return -1;
}
int main()
{
int params[] = { 3, 4, 5, 23 };
std::cout << check(params);
}
Operators * / have a higher precedence than + -, so operator[i](A, operator[j](B, C)) solution doesn't really work.
You can write a little string calculator, and cycle through char-operators:
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
double calculate(std::string str)
{
// calculator there
return -1;
};
int main()
{
std::vector<char> op = {'+', '-', '*', '/'};
std::vector<int> a = { 96, 3, 10, 42 };
for (auto op1: op)
for (auto op2: op)
{
std::stringstream ss;
ss << a[0] << op1 << a[1] << op2 << a[2];
double result = calculate( ss.str());
if (std::abs(a[3] - result) < 1E-6)
std::cout << ss.str() << " = " << a[3];
else
std::cout << ss.str() << " = " << result << " != " << a[3];
}
}

Integer value assignment in c++

I'm pretty new to C++ and I have the following simple program:
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
cout << sum; // outputs 15
return 0;
}
I receive always the output 15, although I've changed the value of b to 6.
Thanks in advance for your answers!
Execution of your code is linear from top to bottom.
You modify b after you initialize sum. This modification doesn't automatically alter previously executed code.
int sum = a + b; writes the result of adding a and b into the new variable sum. It doesn't make sum an expression that always equals the result of the addition.
There are already answers, but I feel that something is missing...
When you make an assignment like
sum = a + b;
then the values of a and b are used to calculate the sum. This is the reason why a later change of one of the values does not change the sum.
However, since C++11 there actually is a way to make your code behave the way you expect:
#include <iostream>
int main() {
int a = 5,b = 10;
auto sum = [&](){return a + b;};
b = 6;
std::cout << sum();
return 0;
}
This will print :
11
This line
auto sum = [&](){return a + b;};
declares a lambda. I cannot give a selfcontained explanation of lambdas here, but only some handwavy hints. After this line, when you write sum() then a and b are used to calculate the sum. Because a and b are captured by reference (thats the meaning of the &), sum() uses the current values of a and b and not the ones they had when you declared the lambda. So the code above is more or less equivalent to
int sum(int a, int b){ return a+b;}
int main() {
int a = 5,b = 10;
b = 6;
std::cout << sum(a,b);
return 0;
}
You updated the b value but not assigned to sum variable.
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
sum = a + b;
cout << sum; // outputs 11
return 0;
}

c++ double type and integer type [duplicate]

This question already has answers here:
Why does division result in zero instead of a decimal?
(5 answers)
Closed 7 years ago.
I want to calculate the result of this formula:
1/1! + 1/2! + 1/3! + 1/4! + ... + 1/10!
Here is my code:
#include <iostream>
#include <cstdlib>
using namespace std;
double func(int );
int main(void) {
int a;
double sum=0;
do{
cout << "input a num: " ;
cin >> a;
}while (a<=0);
for (int i=1; i<a+1; i++) {
sum = sum + (double)(1/func(i));
}
cout << sum << endl;
return 0;
}
double func(int num)
{
if(num>0)
return num*func(num-1);
else
return 1;
}
I am curious about why I have to use double type for func to pass back.
If I used int type to pass, like this
int func(int num)
The result of sum will be not correct.
That would work. Infact, you don't need the typecast (double)(1/func(i))
Change the line as follows:
sum = sum + (1.0/func(i));

How to return multiple values from a function in c++?

I know this has been asked before but I still don't know how to do it. I Have to write a function which returns the number of times 2, 5 and 9 appear in an array.
include <iostream>
int twofivenine(int array[], int n)
{
int i = 0;
int num_2 = 0;
int num_5 = 0;
int num_9 = 0;
for ( i = 0; i < n; i++ ){
switch(){
case (array[i] == 2):
num_2++;
case (array[i] == 5):
num_5++;
case (array[i] == 9):
num_9++;
}
}
return ;
}
int main()
{
int array[6] = {2,2,3,5,9,9};
std::cout << "2: 5: 9:" << twofivenine(array, 6) << std::endl;
}
I'm just not sure how to return (num_2, num_5, and num_9)
Can use std::tuple
std::tuple<int, int, int > twofivenine( int array[], int n)
{
//
return make_tuple( num_2, num_5, num_9 );
}
auto x = twofivenine( array, 6 );
std::cout << std::get<0>( x ) << '\n'
<< std::get<1>( x ) << '\n'
<< std::get<2>( x ) << '\n' ;
There are a number of ways to approach this problem.
Pass the values by reference. You can call a function such as the following:
Example:
void foo(int &a, int &b, int &c)
{
// modify a, b, and c here
a = 3
b = 38
c = 18
}
int first = 12;
int second = 3;
int third = 27;
foo(first, second, third);
// after calling the function above, first = 3, second = 38, third = 18
Store the values to return in a data type. Use a data type from the standard library such as std::vector, std::set, std::tuple, etc. to hold your values then return that entire data member.
Example:
std::vector<int> foo()
{
std::vector<int> myData;
myData.pushBack(3);
myData.pushBack(14);
myData.pushBack(6);
return myData;
}
// this function returns a vector that contains 3, 14, and 6
Create an object to hold your values. Create an object such as a struct or a class to hold your values and return the object in your function.
Example:
struct myStruct
{
int a;
int b;
int c;
};
myStruct foo()
{
// code here that modifies elements of myStruct
myStruct.a = 13;
myStruct.b = 2;
myStruct.c = 29;
return myStruct;
}
// this function returns a struct with data members a = 13, b = 2, and c = 29
The method you choose will ultimately depend on the situation.
Pass objects in by reference, ie
void twofivenine(int array[], int n, int &num_2, int &num_5, int &num_9)
{
//Don't redeclare num_2...
}
Call like so:
int num_2, num_5, num_9;
twofivenine(array, 6, num_2, num_5, num_9);
Return a struct by value which has the counts as the data members:
struct Result {
int num_3;
int num_5;
int num_9;
};
Result twofivenine(int array[], int n)
{
.
.
.
return Result{num_2, num_5, num_9};
}
and in main:
Result result(twofivenine(array, 6));
std::cout << "2: " << result.num_2 << "5: " << result.num_5 << "9: " << result.num_9 << std::endl;
Most compilers will do RVO (return-value-optimization) where the twofivenine function will directly write to the result struct avoiding a struct copy.

Returning and outputting 2 integers from 1 function

i have to write a code that has a function that takes two integers and returns x as (a + b) and y as (a * b) and when i run it, it only outputs y. Why doesnt it output (or return) x?
#include <iostream>
using namespace std;
int math (int a, int b) {
int x, y;
x = a + b;
y = a * b;
return x, y;
}
int main() {
cout << math (5,3);
getchar();
getchar();
return 0;
}
The return type of math is int, so this is what it returns (a single integer).
The expression x, y uses the comma operator. The comma operator evaluates x, discards its value, and then evaluates and returns y. In other words, return x, y is equivalent to return y.
You could use std::pair<int,int> to return a pair of integers.
The line
return x, y;
does not do what you expect. The comma operator returns only the value after the last comma - in this case, y. To return multiple values, you should use a struct or class containing both.
You can only return one thing. You can put those in a struct, and return it. Simpler example.
struct xy {
int x;
int y;
};
xy math(int a, int b) {
xy pair;
int x, y;
pair.x = a + b;
pair.y = a * b;
return pair;
}
There are two ways to make a function return more than one value. The
first is to use out parameters, either references or pointers:
void
math( int a, int b, int& sum, int& product )
{
sum = a + b;
product = a * b;
}
int
main()
{
int s;
int p;
math(5, 3, s, p);
std::cout << s << ' ' << p << std::endl;
return 0;
}
The other is to define a class to contain the two values:
struct MathResults
{
int sum;
int product;
};
MathResults
math( int a, int b )
{
return MathResults{ a + b, a * b };
}
std::ostream&
operator<<( std::ostream& dest, MathResults const& value )
{
dest << value.sum << ' ' << value.product;
}
int
main()
{
std::cout << math( 5, 3 ) << std::endl;
return 0;
}
In most cases, the second solution is to be preferred.