I am trying to solve a problem that says:
Write a program that computes the difference between non-negative integers.
Each line of the input consists of a pair of integers. Each integer is between 0 and 10 raised to 15 (inclusive). The input is terminated by end of file.
For each pair of integers in the input, output one line, containing the absolute value of their difference.
Here is my solution:
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int x;
int y;
int z;
cin >> x >> y;
if(x && y <= 1000000000000000){
z=x-y;
cout << std::abs (z);
}
}
But the problem is my answer is wrong, please help me correct my answer and explain why it was wrong.
For starters usually the range of valid values for objects of type int
is less than 1000000000000000
.
You should use an integer type wide enough to store such big values. An appropriate type is unsigned long long int
because according to the assignment entered values are non-negative.
Otherwise you will need also to check that the values are not negative that is greater than or equal to zero.
Also the condition in the if statement
if(x && y <= 1000000000000000){
is wrong. It is equivalent to
if(x && ( y <= 1000000000000000 )){
that in turn is equivalent to
if( ( x != 0 ) && ( y <= 1000000000000000 )){
it is not the same as
if ( ( x <= 1000000000000000 ) && ( y <= 1000000000000000 ) ){
The program can look the following way
#include <iostream>
int main()
{
const unsigned long long int UPPER_VALUE = 1000000000000000;
unsigned long long int x, y;
while ( std::cin >> x >> y )
{
if ( x <= UPPER_VALUE && y <= UPPER_VALUE )
{
std::cout << "The difference between the numbers is "
<< ( x < y ? y - x : x - y )
<< std::endl;
}
else
{
std::cout << "The numbers shall be less than or equal to "
<< UPPER_VALUE
<< std::endl;
}
}
}
If for example to enter these values
1000000000000000 1000000000000000
1000000000000001 1000000000000000
1 2
then the program output will look like
The difference between the numbers is 0
The numbers shall be less than or equal to 1000000000000000
The difference between the numbers is 1