Game Development Reference
In-Depth Information
A Simple Arithmetic Calculator
We will now write a simple program that can show the results of the arithmetic operators. Listing 3-1
shows the code that will take two numbers and add them together. This sample code was created
using Xcode and the main function is suitable for creating command-line programs for OS X.
Listing 3-1. Adding Two Numbers
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
cout << "Enter your first number: " << endl;
float number1 = 0.0f;
cin >> number1;
cout << "Enter your second number: " << endl;
float number2 = 0.0f;
cin >> number2;
float result = number1 + number2;
cout << "The result of adding your two numbers is: " << result << endl;
return 0;
}
We once again use cin and cout to communicate with users and ask them to enter two numbers.
We then store the result of an addition in the variable result and print the output to the console.
An example of the output from this program is shown here:
Enter your first number:
40
Enter your second number:
10
The result of adding your two numbers is: 50
Listing 3-2 shows a subtraction version of this program.
Listing 3-2. Subtracting Two Numbers
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
cout << "Enter your first number: " << endl;
float number1 = 0.0f;
cin >> number1;
cout << "Enter your second number: " << endl;
float number2 = 0.0f;
cin >> number2;
 
Search WWH ::




Custom Search