+ 1
Can anybody help me?(C++)
The output of this programm mus. t be 4 random,NOT similar numbers.But sometimes the output of this programm is 4 random,but SIMILAR numbers.How Ican fix it? https://code.sololearn.com/cmh43uFTIYWy/?ref=app
9 Respostas
+ 2
cleaned your code a little bit and corrected what was wrong with your code (check out getting parameters by refrence) if you don't know the difference between getting variables by reference and value is definitely check it.(if you did this with arrays this problem wouldn't happen)
additionally your program is running functions a lot of time to simply get 4 different numbers for example:
proverka1(1,1,2,5) it may call proverka1(5,1,2,5) then it may call
1. proverka1(2,1,2,5) or even more ridiculous case
2.proverka1(1,1,2,5) which is our initial state 3 calls we're back to first step
https://code.sololearn.com/c5OZCig4m0Pi/?ref=app
+ 2
1.use an array it's more compact and readable
2.instead of making 4 numbers first and then checking them it's better to make the 1st number and then continue making another number untill you get a different one and for the 3rd number check it with the first two and so on
+ 1
Ok,but why does it work so?(Sorry,that I did not write anything for a long time)
+ 1
to be more precise your code's problem was that you passed variables by value so didn't change the real variables for example if you run this code
void func(int a)
{
a = 10
}
int main()
{
int t = 5;
func(t);
std::cout << t
}
the output will be 5 not 10 (which you expected from your code) cause a value of variable "t" is sent to function "func" and in the function this value is known as "a". but with passing by reference(arrays which are const pointers and using "&" to reference) you actually pass the variable itself(address of the value) so changing it in the function means changing the real value not a copy of it's value.
+ 1
you're welcome
+ 1
both of them take lvalue
both of them change the value of the sent variable in its original scope
first one takes an address so you send &var := address of the variable
and for changing its value you have to first dereference it by "*" operator:
*x = newValue
second one makes an alias of the sent variable in the function scope so you can treat it as the original variable
0
I am not sure,but I think that I began to understand...
Thank you very much
0
I think you have already tired of my questions, but if it's not hard, can you explain to me how this syntax of passing by reference works?In sololearn I saw this syntax:
void myFunc(int *x) {
*x = 100;
}
int main() {
int var = 20;
myFunc(&var);
cout << var;
}
But you use this one:
void myFunc(int &x) {
x = 100;
}
int main() {
int var = 20;
myFunc(var);
cout << var;
}
What are difference?
And how it works?
P.S. Thank you in advance
0
Thak you twice!
You helped me a lot