Подтвердить что ты не робот

Найдите наименьшее среди 3 чисел в С++

Есть ли способ сделать эту функцию более элегантной? Я новичок в С++, я не знаю, есть ли более стандартизированный способ сделать это. Может ли это быть превращено в цикл, поэтому количество переменных не ограничено, как с моим кодом?

float smallest(int x, int y, int z) {

  int smallest = 99999;

  if (x < smallest)
    smallest=x;
  if (y < smallest)
    smallest=y;
  if(z < smallest)
    smallest=z;

  return smallest;
}
4b9b3361

Ответ 1

Есть ряд улучшений, которые можно сделать.

Вы можете использовать стандартные функции, чтобы сделать его более понятным:

// Notice I made the return type an int instead of a float, 
// since you're passing in ints
int smallest(int x, int y, int z){
    return std::min(std::min(x, y), z);
}

Или еще лучше, как указано в комментариях:

int smallest(int x, int y, int z){
    return std::min({x, y, z});
}

Если вы хотите, чтобы он работал с любым количеством int, вы могли бы сделать что-то вроде этого:

int smallest(const std::vector<int>& intvec){
    int smallest = std::numeric_limits<int>::max(); // Largest possible integer
    // there are a number of ways to structure this loop, this is just one
    for (int i = 0; i < intvec.size(); ++i) 
    {
        smallest = std::min(smallest, intvec[i]);
    }
    return smallest;
}

Вы также можете сделать его общим, чтобы он работал на любом типе, а не только на ints

template <typename T>
T smallest(const std::vector<T>& vec){
    T smallest = std::numeric_limits<T>::max(); // Largest possible integer
    // there are a number of ways to structure this loop, this is just one
    for (int i = 0; i < vec.size(); ++i) 
    {
        smallest = std::min(smallest, vec[i]);
    }
    return smallest;
}

Ответ 2

Если возможно, я рекомендую использовать С++ 11 или новее, что позволяет вам вычислить желаемый результат без реализации вашей собственной функции (std:: min). Как уже указывалось в одном из комментариев, вы можете сделать

T minimum(std::min({x, y, z}));

или

T minimum = std::min({x, y, z});

в котором хранится минимум переменных x, y и z в переменной minimum типа T (обратите внимание, что x, y и z должны иметь одинаковые типа или должны быть неявно конвертируемы к нему). Соответственно, то же самое можно сделать для получения максимума: std::max({x, y, z}).

Ответ 3

apart min, что позволяет писать return min (x, min (y, z)), существует тройной оператор:

float smallest(int x, int y, int z){
  return x < y ? (x < z ? x : z) : (y < z ? y : z);
}

Ответ 4

smallest=(x<((y<z)?y:z)t)?x:((y<z)?y:z);

Предположим,

x is one;
y is two;
z is three;

smallest = (one < ((two < three) ? two:three)) ? one:((two < three) ? two:three)

Ответ 5

Есть предложение включить это в библиотеку С++ под N2485. Предложение прост, поэтому я включил осмысленный код ниже. Очевидно, это предполагает вариационные шаблоны.

template < typename T >
const T & min ( const T & a )
{ return a ; }

template < typename T , typename ... Args >
const T & min ( const T & a , const T & b , const Args &... args )
{ return std :: min ( b < a ? b : a , args ...); }

Ответ 6

Небольшая модификация

 int smallest(int x, int y, int z){
    int smallest = min(x,y);
    return min(smallest,z);
    }

Ответ 7

В вашей версии вы найдете наименьшее значение, только если оно меньше 99999.

Вы должны сравнить все три значения вместе. Кроме того, вы получаете int, но возвращаете float. Либо вы должны решить, какие типы значений вы хотите обработать, либо создать обобщенную версию, которая работает с любым видом, который можно сравнить:

#include <algorithm>

template<class T>
T smallest(T x, T y, T z)
{
  return std::min(x, std::min(y, z));
}

EDIT:

Два способа улучшить код в том, что работает с vector:

#include <cstdio>
#include <algorithm>
#include <vector>

// Use a built-in function to retrieve the smallest value automatically
template<class T>
T smallest1(const std::vector<T> &values)
{
  return *std::min_element(values.begin(), values.end());
}

// Go through the vector manually
template<class T>
T smallest2(const std::vector<T> &values)
{
  // Get the first value, to make sure we're comparing with an actual value
  T best_so_far = values.front();
  // For all the other values in the vector ...
  for(unsigned i = 1; i < values.size(); ++i) {
    // ... replace if the new one is better
    if(values[i] < best_so_far)
      best_so_far = values[i];
  }
  return best_so_far;
}

int main()
{
  // Try out the code with a small vector
  std::vector<int> test;
  test.push_back(6);
  test.push_back(5);
  test.push_back(7);

  printf("%d\n", smallest1(test));
  printf("%d\n", smallest2(test));

  return 0;
}

Ответ 8

1) Простое решение:

int smallest(int x, int y, int z)
{
    return std::min(std::min(x, y), z);
}

2) Лучшее решение (с точки зрения оптимизации):

float smallest(int x, int y, int z)
{
  return x < y ? (x < z ? x : z) : (y < z ? y : z);
}

3) ваше решение Модифицировано (просто, но не эффективно):

int smallest(int x, int y, int z)
{

  int smallest = x;

  if (y < smallest)
     smallest=y;
  if(z < smallest)
     smallest=z;
  return smallest;
}

4) Любое число номеров:

Для n чисел сохраните его в массиве (array [n]), Сортируйте массив и возьмите массив [0], чтобы получить наименьшее значение.

    //sort the elements in ascending order
    for(int i=0;i<n;i++)
    {
      if(array[i]>array[i+1])
      {
        int temp = array[i];
        array[i] = array[i+1];
        array[i+1] = temp;
      }
    }

    //display smallesst and largest
    cout<<"Smallest: "<<array[0];
    cout<<"Largest: "<<array[n-1];   //not needed in your case
    }

Ответ 9

Вы можете сохранить их в векторе и использовать std::min_element.

Например:

vector<int> values;
values.push_back(10);values.push_back(1);values.push_back(12);

int min = *std::min_element(values.begin(),values.end());

Ответ 10

Или вы можете просто использовать define, чтобы создать макрофункцию.

#define min(x,y,z) (x < y ? (x < z ? x : z) : (y < z ? y : z))