Domanda

I want to print the amount of numbers that are within the range of two numbers (those two numbers included).

I have created this simple code:

#include <iostream>

int main(int argc, char *argv[]) {
  int one = -5;
  int two = 5;
  unsigned int count = 0;

  int min = std::min(one, two);
  int max = std::max(one, two);

  while (min <= max) {
    count++;
    min++;
  }

  std::cout << count << std::endl;

  return 0;
}

In this example I use -5 to 5 and it correctly prints 11.

How can I improve this algorithm so that it works without problem with numbers ranging from for example -1 billion to 1 billion?

Or is the code fine as it stands?

È stato utile?

Soluzione

The number of numbers in that range is simply their difference + 1:

count = max - min + 1;

Or, without evaluating which is the max and which the min, use the absolute value of the difference

count = std::abs(one - two) + 1;

Altri suggerimenti

Maybe I missed something, but

#include <iostream>

int main(int argc, char *argv[]) {

    int one = -5;
    int two = 5;
    unsigned int count = std::abs(one-two)+1;

    std::cout << count << std::endl;

    return 0;
}

should do exactly what you want?

This will give 11 for -5 and 5, which is in fact the count of numbers betweeen -5 and 5, including both. If you want it to print 10, as you said in your quetion you have to remove the +1.

You need to use an integral type that can contain such range of numbers. At present the greatest fundamental signed integral type in C++ is long long int You can get the range of numbers it can store by using expressions

std::numeric_limits<long long int>::min() and std::numeric_limits<long long int>::max()

structure std::numeric_limits is defined in header <limits>

For example

#include <iostream>
#include <limits>

int main()
{
   std::cout << std::numeric_limits<long long int>::min() << " - "
             << std::numeric_limits<long long int>::max() << std::endl;
}

Also it would be better if the program would ask the user to enter the two numbers. For big ranges it is better to use a simple arithmetic expression to get the counter instead of using the loop.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top