c++ – I want to display the amount of negative numbers entered using functions

Question:

#include <iostream>
#include <locale.h>

using namespace std;

int getnegativo(int a, int b);

int main()
{
    setlocale(LC_ALL, "portuguese");
    int cont, cot=0;

    do {
        cout << "digite um valor: ";
        cin >> cont;

      cot = getnegativo(cont, cot);

    }while (cont != -1);

    cout << "número de valores negativos digitados: " << cot;

    cout << "\n\n" << endl;
    return 0;
}


int getnegativo(int a, int b){
if (a<0)
    b++;
}

Answer:

I'll help you on the way you're going, but there are a lot of things that would be better done differently. One of the changes is that I would probably pass the argument by reference instead of making a return , but I probably haven't learned how to use this yet, so it goes with the simpler way.

#include <iostream>
#include <locale.h>
using namespace std;

int getnegativo(int a, int b){
    if (a < 0)  b++;
    return b;
}

int main() {
    setlocale(LC_ALL, "portuguese");
    int cont, cot = 0;
    do {
        cout << "digite um valor: ";
        cin >> cont;
      cot = getnegativo(cont, cot);

    } while (cont != -1);
    cout << "número de valores negativos digitados: " << cot;
    cout << endl << endl;
}

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

I would start thinking about what you are using. Why use locale in every application if it doesn't have any function in the code? It's even worse for being something from C and not native to C++.

Scroll to Top