while code does not make the correct condition

Asked

Viewed 126 times

2

I need to create a code that reads only one double and register in two variables the "smallest so far" and the "biggest so far", I can even complete a cycle successfully but after that it prints out any value I insert.

I tried some ways how to do a function, go back to looping but would be defective.

while(cin>>num1){
    cout << "maior ate agora " << num1 << endl;
    cin >> num2;
    if(num2 > num1)
        cout << "maior ate agora " << num2;
    else
        cout << "maior ate agora " << num1;
}
  • Put the rest of the code to see if there is an error somewhere else. Something else. When should you stop asking? There is no end.

  • That’s basically it, except for the statement, double input = 0; double minor = 0; double major = 0;

  • 1

    And if the mistake is in it?

  • Yeah, I edited a few seconds ago :D

2 answers

1

The comparison is being made in the wrong way as it always compares with the first. Change your while:

while (num1 >= 0) {
   cin >> num1;
   if(num1 > maior) {
      maior = num1;
      cout << "maior ate agora " << maior << endl;
   }
}

1


The code has some problems and the biggest one is that the comparison is always being made with the first number and not with the biggest one so far. Another serious problem is not having an output way. I switched so that a negative number generates the output. Can be changed to another criterion if you want to accept negatives.

#include <iostream>
using namespace std;

int main() {
    int maior = 0, numero = 0;
    while (numero >= 0) {
        cin >> numero;
        if (numero > maior) {
            maior = numero;
            cout << "maior ate agora " << maior << endl;
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I knew it was something like this, I tried to make some ideas of assignments but it didn’t work, btw, thanks ^^

Browser other questions tagged

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