Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to calculate difference between two numbers?

Tags:

c++

math

I'm about to do this in C++ but I have had to do it in several languages, it's a fairly common and simple problem, and this is the last time. I've had enough of coding it as I do, I'm sure there must be a better method, so I'm posting here before I write out the same long winded method in yet another language;

Consider the (lilies!) following code;

// I want the difference between these two values as a positive integer int x = 7 int y = 3 int diff; // This means you have to find the largest number first  // before making the subtract, to keep the answer positive if (x>y) {       diff = (x-y); } else if (y>x) {      diff = (y-x); } else if (x==y) {     diff = 0; } 

This may sound petty but that seems like a lot to me, just to get the difference between two numbers. Is this in fact a completely reasonable way of doing things and I'm being unnecessarily pedantic, or is my spidey sense tingling with good reason?

like image 261
jwbensley Avatar asked May 14 '12 19:05

jwbensley


People also ask

What is the formula to calculate difference?

Percentage Difference Formula:Percentage difference equals the absolute value of the change in value, divided by the average of the 2 numbers, all multiplied by 100. We then append the percent sign, %, to designate the % difference.

What is the difference between 3 and 5?

if we are told to find the difference between 3 and 5, then we usually subtract 3 from 5 ,5-3=2 and thus, we say that the difference is 2.

What is the absolute difference between two numbers?

The absolute difference of two real numbers x, y is given by |x − y|, the absolute value of their difference. It describes the distance on the real line between the points corresponding to x and y.


2 Answers

Just get the absolute value of the difference:

#include <cstdlib> int diff = std::abs(x-y); 
like image 84
juanchopanza Avatar answered Oct 12 '22 09:10

juanchopanza


Using the std::abs() function is one clear way to do this, as others here have suggested.

But perhaps you are interested in succinctly writing this function without library calls.

In that case

diff = x > y ? x - y : y - x; 

is a short way.

In your comments, you suggested that you are interested in speed. In that case, you may be interested in ways of performing this operation that do not require branching. This link describes some.

like image 35
ShinTakezou Avatar answered Oct 12 '22 09:10

ShinTakezou