Ezekiel
Ezekiel

Reputation: 89

Why my c++ algorithm is always returning the same value for Min and Max figure of a number?

I have been writing some simple algorihtms and I am facing with a problem. I am writing an algorithm for showing the minimum and the maximum figure of a number. It works, but it only returns the maximum for both cases and I can't figure why. Thanks a lot !!!

#include <iostream>

using namespace std;

void Citire(int& n)
{ cout  <<"\nDa numarul:";
  cin   >>n;
  while (n<=0)
    {cout<<"ai gresit, da natural:";
     cin >>n;
    }
}

int CifMinMax(int n)
{
    int Max = 9;
    int Min = 0;
    int UltCif;

    while (n>0)
    {
        UltCif = n % 10;

        if (UltCif < Min)
          Min = UltCif;

        if (UltCif > Max)
            Max = UltCif;

    n = n/10;
    }

    return Max, Min;
}

int main()
{
    int n;
    int Min;
    int Max;

    Citire(n);
    Min = CifMinMax(n);
    Max = CifMinMax(n);

    cout <<endl<<Min<<" este cifra minima a numarului, iar "<<Max<<" este cifra maxima a numarului." << endl;
    return 0;
}

Upvotes: 0

Views: 372

Answers (1)

Paul
Paul

Reputation: 13238

return Max, Min;

This line actually returns Min discarding Max. Read about operator , it evaluates its operands from left to right and returns the last one, that's why you are getting the same values.

You need something like this:

std::pair<int, int> CifMinMax(int n)
{
    // ...
    return std::make_pair(Min, Max);
}

std::pair<int, int> MinMax = CifMinMax(n);
Min = MinMax.first;
Max = MinMax.second;

Upvotes: 8

Related Questions