How to initialize multiple variables in C++ to the same value? - c++

Would this kind of variable assignment work?
double a = 2.0,
x, y, z = 0.5;
Would the second line of code work properly and initialize x, y, z each to 0.5?

Your code leaves x and y uninitialized. However, a slight rearrangement can save you from repeating an initial value:
double a = 2.0, x = 0.50, y = x, z = x;
Variables that are declared earlier in a declaration are in scope of later declarations.
This is sometimes particularly useful when evaluating one initializer may have a non-trivial runtime cost. For example, in the following nested loop where m is a multimap:
for (auto it = m.begin(), kt = it, e = m.end(); it != e; it = kt)
{ // ^^^^^^^^^^^^^^^^^^^^^^^
// handle partition
for (; kt != e && kt->first == it->first; ++kt)
{
// ... handle equal-range
}
}

No, only z would be initialized .You have to write it like this:
double x = 0.50, y = x, z = x;
But you can write an assignment like this:
double x, y, z;
x = y = z = 0.50;

Simply No. Only z will be initialized.
If you try to print them afterwards
std::cout << a << " " << x << " " << y << " " << z;
you will get this kind of warning from the compiler:
warning: 'x' is used uninitialized in this function
For the sake of clarity I would use the second option that Rabbid76 suggested:
double x, y, z;
x = y = z = 0.50;

The second line of code:
double x;
x = 50.1;
actually has a return value. Usually, it is not caught, or used, but it is there. So x = 50.1 returns the value 50.1.
This implies that you could do:
double x,y,z;
x = y = z = 50.1;
And the value will make its way up the chain where x = y returns and the value isn't caught again. After that line is executed, x, y and z will all have the value 50.1.

If you want to assign to all three variables, write
x = y = z = 0.5;
which is equivalent to
x = (y = (z = 0.5));
The code that you present only assigns to z.

You can achieve what you want doing this:
x = y = z = 0.50;

You could do that in a single line like this:
double x = 0.5, y = 0.5, z = 0.5;

Related

In C++, can you define a variable in terms of other variables that have already been defined? [duplicate]

This question already has answers here:
C++ initialize variable based on condition [closed]
(4 answers)
How to let a variable be dependent on other variables inside a class?
(6 answers)
How to initialize a static variable with another static variable?
(1 answer)
Closed 2 years ago.
For example, can I define a variable "z" in terms of variables I already defined called "x" and "y" (yes I know these are horrible naming conventions but it's an example). Like this:
int x = 0;
int y = 0;
int z = x * y;
Can you do something like that and just go on with your program or will you get error messages?
You may be interested in lambdas:
int x = 0;
int y = 0;
auto z = [&x, &y](){ return x * y; };
This code does exactly what you are requesting: calling the z() function would always give you the result that is the multiplication of the x and y variables:
int v = z();
assert(v == x * y);
Even if x or y change you would always get their multiplication:
int x = 0;
int y = 0;
auto z = [&x, &y](){ return x * y; };
assert(z() == 0);
x = 1;
y = 2;
assert(z() == 2);
can I define a variable "z" in terms of variables I already defined called "x" and "y"
int z = x * y;
Totally possible to define z that way. Most if not all languages should allow that basic definition. Except, perhaps you have to be careful with overflow issue. If later in your program you may assign x and y to very large value, then z could overflow. It may be better to do:
long long z = x * y;
Yes, you can.
Also,
int x = 1, y = x;
int z=x*y;
y = x; is possible.

How to sum two lists correctly?

My task is to form a list Z by summing the elements of two lists.
If it is simpler, then I have two lists X {x1, x2, ... xn} & Y {y1, y2, ..yn} - >> I need to form Z.
X & Y size is the same.
Zi = Xi + Yi
I solve this problem, but I can’t. How can I solve the problem?
Code:
void IndividualTask(list<float>& lisX, list<float>& lisY) {
list<float> Z;
int i = 0;
list<float>::iterator x = lisX.begin();
list<float>::iterator y = lisY.begin();
for (list<float>::iterator it = lisX.begin(); it != lisX.end(); ++it) {
Z.push_back((x + i) + (y + i));
i++;
}
}
You need to make sure you increment both iterators so you have access to both elements:
std::list<float> IndividualTask(std::list<float>& lisX, std::list<float>& lisY) {
std::list<float> Z;
for (auto x = lisX.begin(), y = lisY.begin(); x != lisX.end() && y != lisY.end(); ++x, ++y) {
Z.push_back(*x + *y);
}
return Z;
}
std::list has no random accesss iterators, which means you can't add an a numeric value to it to advance them by several positions. You can only increment or decrement such an iterator by one at a time.
So the idea is to take two iterators and increment both inside the loop, add the values of both iterators and push the result to Z. Something like this:
void IndividualTask(const list<float>& lisX, const list<float>& lisY) {
list<float> Z;
auto x = lisX.begin();
auto y = lisY.begin();
while(x != lisX.end() && y != lisY.end()) {
Z.push_back(*x + *y);
++x;
++y;
}
}
Research std::accumulate in your favorite C++ reference:
std::list<float> numbers;
//...
const float sum = std::accumulate(numbers.begin(), numbers.end(), 0.0);

Variables out of scope in main when called by reference by a function in C++

I have made the following code, whose output should generate a point uniformly at random on the unit circle centered at the origin:
#include "unif.h"
#include <iostream>
#include <cmath>
using namespace std;
void point_on_circle(double& x, double& y)
{
double r;
do
{
double x = unif(-1.,1.);
double y = unif(-1.,1.);
double r = x*x + y*y;
}
while (r >=1.0);
x = x / sqrt(r);
y = y / sqrt(r);
}
int main()
{
cout << "Pair of points on the circle found is " << x << " and " << y << endl;
cout << "Let's verify: x^2+y^2=" << x*x+y*y << endl;
return 0;
}
The header "unif.h" is just a file that contains a function void unif(double x, double y), that produces uniformly random numbers in the interval (x,y), and it works perfectly (already tested).
The problem is that when I build the program then it gives me (of course) the error in the main:
"error: 'x' was not declared in this scope"
which is clear since of course x is defined outside the main and never defined in main(). I cannot figure out how to tell the compiler that the values of x and y found by the function point_on_circle should be "carried" inside the main. How could I fix this code?
Thanks in advance
In your main method you did not declare a variable called x nor y. Moreover, you also have scoping issues in your point_on_circle(double& x, double& y) function with the variable r.
Please review C++ scoping.
Because you defined x in the do-while loop, so you cannot use it outside the loop, since those definitions hide the parameters x and y. Define it before the loop:
void point_on_circle(double& x, double& y)
{
double r;
do
{
x = unif(-1.,1.);
y = unif(-1.,1.);
r = x*x + y*y;
}while (r >=1.0);
x = x / sqrt(r);
y = y / sqrt(r);
}
You have a few issues.
1) you need to declare x and y inside main.
2) you never, ever actually call point_on_circle. At all.
3) finally, as others noted, you mask parameters x and y in your do loop.
With all of that said, it looks like you're attempting to find a random point on the unit circle. with that in mind, I would remove the do loop entirely and just do this:
void point_on_circle(double& x, double& y)
{
double r;
x = unif(-1.,1.);
y = unif(-1.,1.);
r = x*x + y*y;
x = x / sqrt(r);
y = y / sqrt(r);
}
It gives the exact same result while avoiding a (potential) endless loop, and certainly avoids useless extra processing.

How to display a variables from digits in C++?

I have 4 variables called: number, x , y, z.
x = 1,
y = 2,
z = 3
I would like the variable number to be able take the values of x, y and z and be able to display value of 123
I have tried this so far:
number = x + y + z; but the answer is 6.
or
number = x << y << z; but the output is not what I want.
Any help would be appreciated.
in C++:
cout << x << y << z
In C:
printf("%d%d%d", x, y, z);
Or to put them in a string:
ostringstream convert; // stream used for the conversion
convert << x << y << z;
std::string result = convert.str();
You can use std::to_string to convert the int to string, then the + operator acts as a concatenation operation.
#include <string>
std::string concatenated = std::to_string(x) + std::to_string(y) + std::to_string(z);
std::cout << concatenated;
Sounds like you may want to convert the characters to strings, perform the string addition, and then convert back to numbers.
This link should help:
[http://www.cplusplus.com/forum/articles/9645/]
You have plenty of ways to get your result :
numerically : number = x * 100 + y * 10 + z
string concatenation as shown by Cyber
directly using characters :
char resul[4];
resul[0] = '0' + x;
resul[1] = '0' + y;
resul[2] = '0' + z;
resul[3] = '\0';
and probably many others ...

Returning multiple values and default parameters in C++

I'm trying to make a function that takes in either 1 or 3 parameters, and returns either 1 or 3 values (based on parameters passed).
If 1 parameter is passed then the function uses default values for the other 2 arguments.
If 3 parameters are passed then it uses those values.
bool foo( bool x, int &y = 0, int &z = 0) {
x = true; y = y + 1; z = z + 2;
return x;
}
Is this possible in C++ or am I confused with Java functions.
You can do it with two functions:
bool foo( bool x, int &y, int &z) {
x = true; // this isn't really what it does, is it?
y = y + 1; z = z + 2;
return x;
}
bool foo(bool x)
{
int a = 0, b = 0;
return foo(x,a,b);
}
Any function always returns only 1 value. Returning 2 or more values is not possible directly.
Indirectly, it happens when you pass parameters by reference. Since the two parameters &y and &z are passed by references, hence changes to them can be reflected back directly.
You can do this by passing by reference..
by doing so you are making a method that points to a memory location.
When that memory location is changed, then your value is changed.
Link
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr233.htm
You cannot do that this way. You can, however, overload that function with different number of parameters, and return, maybe, a std::vector or std::list with the results.
EDIT:
Being more sophisticated, you can use tuples for that:
typedef boost::tuple<bool,int,int> my_data_t;
my_data_t my_tuple(true, 1, 0);
then, you define your function like this:
bool foo( my_data_t & t)
{
t.get<0>() = true;
int& y = t.get<1>();
y = y+1;
int& z = t.get<2>();
z = z+2;
return t.get<0>();
}
and call it this way:
bool result = foo ( my_tuple );
then, out of the function, you'll see my_tuple.get<1>() (the corresponding to y) as 2 (1+1).
I am not sure what you are trying to do, but you can kind of return multiple values of different type using boost::tuple.
boost::tuple<bool, int, int> foo( bool x, int y = 0, int z = 0) {
x = true; y = y + 1; z = z + 2;
return boost::make_tuple(x, y, z);
}
int main() {
boost::tuple<bool, int, int> result = foo(x, 1, 2);
std::cout << boost::get<0>(result) << boost::get<1>(result) << boost::get<2>(result);
}
You could also use boost::optional, if you only want to return x, if only 1 parameter is passed.
Btw. tuple is available in C++11 too.