+ 1
#include<iostream> using namespace std; int main () { int a,b; int sum=a+b; cout<<"enter a number"; cin>>a; cout<<"enter another number"; cin b; cout<<" sum is"<<sum<<endl; return 0; }
I have used there respective codes but I didn't receive sum as an addition of two numbers instead the ans was a vague number. what is wrong with the above code?
17 odpowiedzi
+ 2
put cin>>b;
+ 1
while programming you need to think all the steps, for example using the same code as you, you wanted to do an addition, but you need to think, what I need to do an addition?. first you need 2 values, but you need to save them, so you declare 2 variables A and B, then you need to put some values inside A and B, so after knowing values you can do the addition and then you do A+B and save them in another variable for so you can print the result.
0
you need to put to sum receive a+b after a and b receive an value
0
ya you are right but I don't understand why ?
0
if you
cout<<sum<<endl;
before
cout<<“enter a number”;
you would get the addition
but you didn't enter any number right?
when a, b changes
sum does not change
sum is just a memory section to save a number ,not a fuction of a+b
so you get the number before you enter a,b
a,b is something else when you add them
0
okey I get it
thank very much
0
put cin >> b
0
here what u have done is like u want to show the ouput of adding up two numbers but what u have done is
shown the sum of a & b before assigning a value to the variables
here the garbage values from stack memory will automatically be assigned to variables a and b
cause u used undefined memories
Thus we u want this code to run correctly
first assign the desired values to a and b, and then add them up, store in "sum" then display!!
hope u got want i meant..
0
#include<iostream>
using namespace std;
int main()
{
int a,b,sum;
cout<<"enter value for a="<<endl;
cin>>a;
cout<<"enter value for b="<<endl;
cin>>b;
sum=a+b;
cout<<"sum="<<sum;
return 0;
}
//this is the right code
0
cin>>b;
0
even though u correct the cin>> u will get the garbage value because u have not stored any value in a and b before adding them .
0
Or if you want a short way😀😁:
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"enter value for a="<<endl;
cin>>a;
cout<<"enter value for b="<<endl;
cin>>b;
cout<<"sum="<<a+b;
return 0;
}
0
you are evaluating sum before a and b are initialized
0
Fix cin>>b and declare sun befor return
0
cin>>b;
U have be attention
0
#include<iostream>
using namespace std;
int main()
{
int a,b,sum;
cout<<"enter value for a="<<endl;
cin>>a;
cout<<"enter value for b="<<endl;
cin>>b;
sum=a+b;
cout<<"sum="<<sum;
return 0;
}
0
put:
cout<<"some of code";
intput:
cin>>_variable_;