# How to Add Decimals in C++

## Design the Algorithm

• 1). Visualize the output of the program. For this example, the output will display the two numbers entered by the user and their sum: 3.278 + 5.09 = 8.368

• 2). The algorithm to product the desired output will request the numbers from the user, then display the sum of both numbers.

• 3). Write down the complete algorithm:

Request user input

Show the result

## Coding the Program

• 1). Identify the resources needed to write the code. In the example we will use console input and output. We will also need to set the number of decimal places to a fixed number. The iostream library is required for the input/output operations. Here is the code:

#include<iostream>

int main()

{

• 2). Declare variables. We will need two variables for the user input. Since we are using decimals we will declare two float variables ("a" and "b").

float a, b;

• 3). Request user input. We will add line breaks ("cout" statements) to format the output.

This is the code for that:

std::cout << "Enter the first number to add: ";

std::cin >> a;

std::cout << "\nEnter the second number to add: ";

std::cin >> b;

std::cout << "\n";

• 4). Output the sum of both numbers.

std::cout << "The sum of " << a << " + " << b << " = "<< a+b << "\n\n";

• 5). Return any value (in our "return()" statement) to terminate the program.

return(0);

}

• 6). Here is the complete code:

/*decimals.cpp*/

#include<iostream>

int main()

{

float a, b;

std::cout << "Enter the first number to add: ";

std::cin >> a;

std::cout << "\nEnter the second number to add: ";

std::cin >> b;

std::cout << "\n";

std::cout << "The sum of " << a << " + " << b << " = "<< a+b << "\n\n";

return(0);

}