0
Write a program that add two numbers and show output.
5 Antworten
+ 1
Hey guys , both of your codes work only for integers
If the user asked the program to add 6.9 and 4.6 then it would show the wrong answer
So shouldn't we assume the inputs and outputs will be in double and use double datatype instead
//this is Dharm's answer, not mine
#include<iostream>
using namespace std;
int main()
{
double a,b; // declaring two numbers
cout<<"Enter two numbers: "; /* input two numbers from user */
cin>>a>>b;
double s; // variable to store result
s=a+b;
cout<<endl;
cout<<" Sum of two numbers is : "<<s;
return 0;
}
0
/* code in c++ to add
two user entered numbers
*/
#include<iostream>
using namespace std;
int main()
{
int a,b; // declaring two numbers
cout<<"Enter two numbers: "; /* input two numbers from user */
cin>>a>>b;
int s; // variable to store result
s=a+b;
cout<<endl;
cout<<" Sum of two numbers is : "<<s;
return 0;
}
output:
Enter two numbers: 2 4
Sum of two numbers is: 6
0
The answer is with Dharm's comment.
Please go learn your basics of C++ before asking this types of question.
0
It would be better if you use functions.
void add(float x,float y)
{
return x+y;
}
Then call this function from main() such as
add(a,b);
Functions makes program simpler and easy to understand. Try using them.