+ 1
🔴 Can anyone explain me this? How come this output? (C++) [CODE IN DESCRIPTION]
Please explain! 👇🏻 https://code.sololearn.com/cuxYuVdPgTdO/?ref=app
7 Respuestas
+ 4
In the scope of method add, you introduce New variables a and b, which are not the same as class attributes a and b.
So you are not working with class attributes a and b in this method.
You could now use another Name for the parameters, like p and q as Syrah Algena wrote.
But this is also a very nice example for the use of this-Operator.
Changing the Code to
void add(int a, float b) {
this->a = this->a + a;
this->b = this->b + b;
}
would also work, while the parameters still called a and b.
this->a referres to the class member a,
a referres to Parameter a
+ 4
Mahima Singh 8 and 8.0 have no difference here because when u adding two float number like
#include <iostream>
using namespace std;
int main(){
float a= 4.5;
float c=a+ a;
cout<<c;
}
U will get 9 not 9.0 so u dint have any issue u can say this is bug but 0.0 and 0 not have any sense its equal hope this example will clear your doubts.
+ 4
As Syrah Algena said you won't get zero after decimal but if you need it ,here is how to do it .
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float a=4.0;
cout<<setprecision(1)<<fixed<<a;
return 0;
}
setprecision will define the amount of numbers to print after decimal.
+ 4
Syrah Algena , Abhay , Abol and G B
Thank you so much each and everyone for clearing my doubts. It was really very helpful! ☺️☺️
Happy coding all of you!!
+ 2
You have defined same variable when u passing values see this function
void add(int a, float b) {
a = a + a;
b = b + b;
}
Here write p and q u will understood why u getting these values
+ 2
Syrah Algena ,G B and Abol
#include <iostream>
using namespace std;
class cmplx {
int a;
float b;
public:
cmplx(int x, float y) {
this -> a = x;
this -> b = y;
}
void add(int a, float b) {
this -> a = a + a;
this -> b = b + b;
}
void display() {
cout << "a: " << a;
cout << "\nb: " << b;
}
};
int main() {
cmplx c(5, 2.4);
c.add(2, 4.0);
c.display();
return 0;
}
Why this is printing
a: 4
b: 8 //why not 8.0???
Why it isn't printing 8.0 in b??
+ 1
G B yes in the given example Compiler getting confused in local and global variables becoz variable names are same a in parameters which she passing and previous defined variable in class .in this case she need to use this keyword