I know how to fix that code, but why for input 0 output is 32765?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
usingnamespace std;
void Addition(int a, int b) {
cout <<a+b<< "\n";
}
int main() {
int x,y;
cout<<"Give numbers to add them:";
cin>>x,y;
Addition(x,y);
return 0;
}
Careful with your streamed input. In C++ the comma operator (,) means something rather different to what it might in this context in other languages. You should have cin >> x >> y;
why for input 0 output is 32765?
y hasn't been initialised, so output is undefined. (It isn't 32765 in cpp.sh).
If you write cin>>x,y;
then it is equivalent to successive statements
#include <iostream>
usingnamespace std;
void Addition(int a, int b)
{
cout << "\n The answer is: " << a + b << "\n";
}
int main()
{
int x{}, y{}; // <--- Always a good idea to initial your variables.
cout<<"Give numbers to add them ( 1 2): ";
cin >> x >> y;
//std::cout << x << " " << y << '\n'; // <--- Used for testing.
Addition(x, y);
return 0;
}
Notice how the blank lines make it easier to read. Also some spaces help the code. Last is the use of "\n"s to break up the output. No one likes reading something where everything is run together.
To the compiler blank lines and white space are ignored. To the reader it makes a big difference.