Program fixing
This program is supposed to take 2 numbers and output the quotient (the answer to a division).
#include <iostream>
int main()
{
std::cout << "Input the number you want to divide and what you want to divide it by (seperated by space).\n";
int input1, input2;
std::cin >> input1 >> input2;
std::cout << input1/input2;
}
However, the program keeps generating inaccurate results, and never gives decimals.
Example
5 2
2
Answer
Alternative 1 - casting the inputs:
When an integer is divided by another, such as input1/input2 the result will also be an integer.
This means that decimal numbers won't be used.
To fix this we can cast the inputs to float or double before the calculation.
#include <iostream>
int main()
{
std::cout << "Input the number you want to divide and what you want to divide it by (seperated by space).\n";
int input1, input2;
std::cin >> input1 >> input2;
std::cout << float(input1)/float(input2);
}
Tecnically we only have to cast one of the inputs to prevent integer division.
Alternative 2 - altering variable datatypes:
We can achieve decimal division by dividing variables that are float or double.
This can easily be achieved by changing the datatype of input1 and input2.
#include <iostream>
int main()
{
std::cout << "Input the number you want to divide and what you want to divide it by (seperated by space).\n";
float input1, input2;
std::cin >> input1 >> input2;
std::cout << input1/input2;
}
int is often used because a decimal number should not be stored in a variable.
Changing the datatype of input1 and input2 changes the core functionality of the program.
If the user input is 25 2.5 the answer from alternative 1 will be 12.5, while the answer for alternative 2 will be 10.
Because of this alternative 2 is arguably a more fitting solution for this program.
However it does change the program in a way that might not have been wanted.
If the program specified that it wanted integers to be the input, then Alternative 1 is more suited.