How to show the largest number typed, using functions?

Asked

Viewed 1,348 times

2

#include <iostream>

using namespace std;

void maior(int a, int b);

int main()
{
    int cont, maior1;
    do {
        cout << "digite um valor: ";
        cin >> cont;
        maior(maior1,cont);
    }while (cont != -1);
    cout << "o maior numero e: " << maior1
    return 0;
}

void maior(int a, int b){
    b=0;
    if (a>b){
        a=b;
    }
}

2 answers

2


I believe that the simplest way is to keep the largest number entered and, after each entry, check whether the number entered is greater than this, if yes becomes the largest entry.

int main(void) {
    int cont, maior = 0;
    do {
        cout << "digite um valor: ";
        cin >> cont;
        //Se o valor entrado for maior que o ultimo passa ele a ser o maior
        if(cont > maior)maior = cont;
    }while (cont != -1);
    cout << "o maior numero e: " << maior;
    return 0;
}

See on Ideone

If you want you can use a function to make the comparison and return the largest of the two numbers:

int getMaior(int a, int b);
int main(void) {
    int cont, maior = 0;
    do {
        cout << "digite um valor: ";
        cin >> cont;
        //Se o valor entrado for maior que o ultimo passa ele a ser o maior
        maior = getMaior(cont, maior);
    }while (cont != -1);
    cout << "o maior numero e: " << maior;
    return 0;
}

int getMaior(int a, int b){
    if (a>b) return a;
    return b;
}

See on Ideone

  • Only I have to use functions.

  • Easy, I’ll edit the answer.

2

#include <iostream>

using namespace std;

int main()
{
    int cont, maior1 = 0;
    do {
        cout << "digite um valor: ";
        cin >> cont;
        maior1 = maior(cont,maior1);
    }while (cont != -1);
    cout << "o maior numero e: " << maior1
    return 0;
}

int maior(int a, int b){
//    b=0;  pq zerou um parâmetro inserido?
    if (a>b)
        return a;
    else
        return b;
}

I don’t understand the reason to use a Function, it must be a thing of course. But... there it is.

  • 2

    I don’t understand why not. Actually it gives better semantics and canonicality. It is true that in simple things like this the need is questionable. But why not get used to doing things in an organized way as if the system were real and complex?

  • Very well quoted. But, as you said, this is a case of "simple things". For this reason I signaled the need for such a function. E, yes, using methods/functions is essential for better code organization.

  • It is quite true that I would use a ready function in this case :) But it is exercise...

  • Haha. Yes, I had to do a lot of that when I started.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.