lundi 17 juin 2019

If statement is always false in c++

I'm working my way thought Bjarne Stroustrup Programming Principles and Practice (4.64 Drill #6) and for some reason I can't get "if" to be true.

  • I've initialized my variables to -1000.
  • I can't initialize to null.
  • I've tried just declaring them
  • I've tried changing the order of my variables.

The problems I've found on stack overflow my code is much different than theirs. I've currently added a vector which I wasn't using prior.

double val1 = 0;  // initialized

double smaller; // initialized
double larger = 0;  // initialized


vector<double> compare; // empty vector of doubles


int main ()
{
    cout << "Please input a value, us | to stop\n"; // put into

    while (cin >> val1)   // cin "get from"
    {
        compare.push_back(val1);

        if (val1 < smaller)
        {
            smaller = val1; // assignment giving a variable a new value
            cout << val1 << " is the smallest so far \n" ;
            compare.push_back(smaller);
        }
        else if (val1 > larger)
        {
            larger = val1;   // assignment giving a variable a new value
            cout << val1 << " is the largest so far \n";
            compare.push_back(larger);
        }
        else
        {
            cout << val1 << " error\n";
        }
    }
}

I can't get smaller "is the smallest so far to print.

I'm teaching myself so any input would be greatly appreciated if anything in my code isn't correct or the best practices please let me know.

Thank You in Advance,

Aucun commentaire:

Enregistrer un commentaire